How to add a new node to a document using java

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 !!

+4
source share
1 answer

You are currently invoking appendChild in the document itself. This will lead to the creation of several root elements, which obviously you cannot do.

You need to find the corresponding element to which you want to add node and add it to this. For example, if you want to add a new element to the root element, yo ucould use:

 document.getDocumentElement().appendChild(newelement); 
+6
source

Source: https://habr.com/ru/post/1414762/


All Articles