How to create xml Document using result of XPath
I'm reading xml document using XPath and I need to create a Document object using the result of XPath evaluation. Can some one tell开发者_运维技巧 me how to do this??
Assuming that your xpath returns a single node, you can do something like:
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
doc.appendChild(doc.importNode(xpathResult, true));
If it returns a node set, you will have to create a root element yourself.
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
doc.appendChild(doc.createElement("root"));
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
doc.getDocumentElement().appendChild(doc.importNode(node, true));
}
refer Create XML document using nodeList
精彩评论