如何使用java在文档中追加新节点

Man*_*ngh 4 java xpath

我有以下updateFile代码,这里我试图在我的xml文件中没有publicationid时添加新节点.

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我使用的是XPathExpression,并且在NodeList中添加了所有匹配的节点nodeList =(NodeList)xpathExp.evaluate(document,XPathConstants.NODESET);

在这里我检查if(nodeList.getLength()== 0)然后这意味着我没有任何传递了publicationid的节点.

如果没有这样的节点,我想创建一个新节点.

在这行newelement.getOwnerDocument().appendChild(newelement); 给出错误(org.w3c.dom.DOMException:HIERARCHY_REQUEST_ERR:尝试插入不允许的节点.).

请建议!!

Jon*_*eet 6

您目前正在调用appendChild文档本身.这最终会创建多个根元素,显然你不能这样做.

您需要找到要添加节点的相应元素,并将其添加到该节点.例如,如果要将新元素添加根元素,则可以使用:

document.getDocumentElement().appendChild(newelement);
Run Code Online (Sandbox Code Playgroud)