我有一个 html 文件:
<html ><head></head> <body> <dtag> <div>TEST</div> </dtag> </body></html>
我想替换整个<dtag>
, 在其中包含内容,文本为“adc”
并保存。我正在使用这个功能:
private void editHTML() {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(strIndexPath));
String strLine;
while ((strLine = br.readLine()) != null) {
sb.append(strLine);
}
Document doc = Jsoup.parse(sb.toString());
// Document doc=Jsoup.parse(strIndexPath,"UTF-8");
String tagName = "dtag";
Elements dTags = doc.select(tagName);
if (dTags != null)
messager.show(dTags.toString());
String strPhp = "<?php $this->DoIt();?>";
for (Element dTag : dTags)
dTag.text(strPhp);
messager.show(dTags.toString());
}
我知道我做到了。但是我不知道如何将它保存到我的 html 文件中。
最佳答案
如果您使用的 PHP 版本早于 7.0.0
, 你可以使用这个 php 开始标签 <script language=php>
而不是 <?php
.
这个不同的 php 开始标签会让 Jsoup 开心:
示例代码
String s = "<html><head></head> <body> <dtag> <div>TEST</div> </dtag> </body></html>";
Document doc = Jsoup.parse(s, "", Parser.xmlParser());
System.out.println("BEFORE:\n" + doc.html());
Elements dTags = doc.select("dtag");
for (Element dTag : dTags) {
dTag.after("<script language=php>$this->DoIt();</script>");
dTag.remove();
}
System.out.println("\n\nAFTER:\n" + doc.html());
输出
BEFORE:
<html>
<head></head>
<body>
<dtag>
<div>
TEST
</div>
</dtag>
</body>
</html>
AFTER:
<html>
<head></head>
<body>
<script language="php">$this->DoIt();</script>
</body>
</html>
引用资料:
关于java - Jsoup:用文本更改标签然后保存在 Java 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36968948/