public static void paintAllNodes(org.w3c.dom.Document domDocument) {
DOMReader reader = new DOMReader();
org.dom4j.Document dom4jdoc = reader.read(domDocument);
}
基本上,我想使用//*
xpath选择所有元素,并在每个元素周围包装<any>
元素标记。
答案 0 :(得分:0)
这是我的代码,它使用xpath表达式//*
来避免你所请求的递归:
public static void main(String[] args) throws DocumentException {
SAXReader saxReader = new SAXReader();
String xml = "<html><head><title>title</title></head><body><h1>title</h1></body></html>";
Document document = saxReader.read(new StringReader(xml));
List nodes = document.selectNodes("//*");
for (Iterator<Node> iterator = nodes.iterator(); iterator.hasNext();) {
Node currentNode = iterator.next();
DefaultElement newElement = new DefaultElement("any");
Element parent = currentNode.getParent();
if (parent != null) {
List contentList = parent.content();
int index = contentList.indexOf(currentNode);
parent.remove(currentNode);
newElement.add(currentNode);
contentList.add(index, newElement);
}
}
Element rootElement = document.getRootElement();
DefaultElement newRootElement = new DefaultElement("any");
document.setRootElement(newRootElement);
newRootElement.add(rootElement);
System.out.println(document.asXML());
}
这是我的输出:
<?xml version="1.0" encoding="UTF-8"?>
<any><html><any><head><any><title>title</title></any></head></any><any><body><any><h1>title</h1></any></body></any></html></any>
希望这有帮助。