I have below the updateFile code, here I am trying to add a new node when there is no publication 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 the above code, I use XPathExpression, and all associated nodes are added to NodeList nodeList = (NodeList) xpathExp.evaluate (document, XPathConstants.NODESET);
Here I check if (nodeList.getLength () == 0), then this means that I do not have a node with the publication passed in.
And if there is no node as such, I want to create a new node.
In this line newelement.getOwnerDocument (). appendChild (newelement); his error message (org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where this is not permitted.).
Please suggest !!
source share