I have below updateFile code, here I am trying to add new node when there is no publicationid in my xml file.
public static void UpdateFile(String path, String publicationID, String url) {
try {
File file = new File(path);
if (file.exists()) {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
document.getDocumentElement().normalize();
XPathFactory xpathFactory = XPathFactory.newInstance();
// XPath to find empty text nodes.
String xpath = "//*[@n='"+publicationID+"']";
XPathExpression xpathExp = xpathFactory.newXPath().compile(xpath);
NodeList nodeList = (NodeList)xpathExp.evaluate(document, XPathConstants.NODESET);
//NodeList nodeList = document.getElementsByTagName("p");
if(nodeList.getLength()==0)
{
Node node = document.getDocumentElement();
Element newelement = document.createElement("p");
newelement.setAttribute("n", publicationID);
newelement.setAttribute("u", url);
newelement.getOwnerDocument().appendChild(newelement);
System.out.println("New Attribute Created");
}
System.out.println();
//writeXmlFile(document,path);
}
} catch (Exception e) {
System.out.println(e);
}
}
In above code I am using XPathExpression and all the matched node are added in
NodeList nodeList = (NodeList)xpathExp.evaluate(document, XPathConstants.NODESET);
Here I am checking if (nodeList.getLength()==0) then that means I don’t have any node with the publicationid passed.
And if there is no node as such I want to create a new node.
In this line newelement.getOwnerDocument().appendChild(newelement); its giving error (org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted. ).
Please suggest!!
You’re currently calling
appendChildon the document itself. That would end up creating multiple root elements, which obviously you can’t do.You need to find the appropriate element where you want to add the node, and add it to that. For example, if you wanted to add the new element to the root element, yo ucould use: