2012-05-28 41 views
4

我有下面的updateFile代碼,在這裏我試圖添加新節點,當我的xml文件中沒有publicationid時。如何在文檔中使用java添加新節點

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); 
     } 
    } 

在上面的代碼中,我使用XPathExpression和所有匹配的節點中節點列表 節點列表被添加=(節點列表)xpathExp.evaluate(文件,XPathConstants.NODESET);

這裏我檢查是否(nodeList.getLength()== 0),那麼這意味着我沒有傳遞了publicationid的任何節點。

如果沒有這樣的節點,我想創建一個新的節點。

在這一行newelement.getOwnerDocument()。appendChild(newelement);它給出的錯誤(org.w3c.dom.DOMException:HIERARCHY_REQUEST_ERR:試圖在不允許的地方插入節點)。

請建議!!

回答

6

您目前正在對文檔本身調用appendChild。那最終會創建多個根元素,顯然你不能這樣做。

您需要在要添加節點的位置找到適當的元素,然後將其添加到該元素。例如,如果你想添加新元素根元素,喲ucould使用:

document.getDocumentElement().appendChild(newelement); 
+0

非常有用的答案! – prabu

相關問題