title: how to append new node in document using java
body: <p>I have below updateFile code, here I am trying to add new node when there is no publicationid in my xml file.</p>
  
  <pre><code>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);
          }
      }
  </code></pre>
  
  <p>In above code I am using XPathExpression and all the matched node are added in 
  NodeList nodeList = (NodeList)xpathExp.evaluate(document, XPathConstants.NODESET);</p>
  
  <p>Here I am checking if (nodeList.getLength()==0) then that means I don't have any node with the publicationid passed.</p>
  
  <p>And if there is no node as such I want to create a new node.</p>
  
  <p>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. ).</p>
  
  <p>Please suggest!!</p>