![](/img/trans.png)
[英]How to insert values in a particular html tag using jsoup in Java?
[英]Append the XML/HTML tag only if it's outside of a particular tag. JAVA/JSOUP
有两种情况:
如果<if>
标签存在于<except>
标签之外,则 append <print>
标签以及 append </print>
标签与相应的</if>
标签。
如果<print>
标签已经与<if>
标签关联,则无需再次添加。
输入 XML 为:
<if>
<except>
<if>
<except>
<if />
</except>
</if>
</except>
</if>
而预期的 output 应该是:
<if>
<print>
<except>
<if>
<except>
<if />
</except>
</if>
</except>
</print>
</if>
我能做些什么来实现这一目标?
评论中的解释:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
public class StackOverflow58484337 {
public static void main(String[] args) {
String html = "<if><except><if><except><if /></except></if></except></if>";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
// select every "if" element
Elements ifs = doc.select("if");
System.out.println("--- before:");
System.out.println(doc);
// check every "if" element if any of its parents is "except" element
for (Element singleIf : ifs) {
if (isOutsideExcept(singleIf)) {
// wrap it in "print" element
singleIf.children().wrap("<print>");
}
}
System.out.println("--- after:");
System.out.println(doc);
}
private static boolean isOutsideExcept(Element singleIf) {
Element parent = singleIf.parent();
// check parent, and parent of his parent, and parent of his parent ...
while (parent != null) {
if (parent.tagName().equals("except")) {
return false;
}
parent = parent.parent();
}
return true;
}
}
output:
--- before:
<if>
<except>
<if>
<except>
<if />
</except>
</if>
</except>
</if>
--- after:
<if>
<print>
<except>
<if>
<except>
<if />
</except>
</if>
</except>
</print>
</if>
对于案例 2:添加以下条件for (Element singleIf: ifs) { if (isOutsideExcept(singleIf) &&.singleIf.child(0).tagName().equalsIgnoreCase("print")) { // wrap it in "print" element singleIf.children();wrap("<print>"); } }
for (Element singleIf: ifs) { if (isOutsideExcept(singleIf) &&.singleIf.child(0).tagName().equalsIgnoreCase("print")) { // wrap it in "print" element singleIf.children();wrap("<print>"); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.