仅当 XML/HTML 标记位于特定标记之外时,才附加该标记。JAVA/JSOUP



有两种情况:

  1. 如果<if>标签存在于<except>标签之外,则附加<print>标签,并在标签后附加</print>相应的</if>标签。

  2. 如果<print>标签已与<if>标签关联,则无需再次添加。

输入的 XML 是:

<if>
<except>
<if>
<except>
<if />
</except>
</if>
</except>
</if>

预期输出应为:

<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;
}
}

输出:

--- before:
<if>
<except>
<if>
<except>
<if />
</except>
</if>
</except>
</if>
--- after:
<if>
<print>
<except>
<if>
<except>
<if />
</except>
</if>
</except>
</print>
</if>

最新更新