【问题标题】:how to append new node in document using java如何使用java在文档中追加新节点
【发布时间】:2012-05-28 18:38:37
【问题描述】:

我有下面的 updateFile 代码,当我的 xml 文件中没有发布 ID 时,我正在尝试添加新节点。

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,并且所有匹配的节点都被添加到 NodeList nodeList = (NodeList)xpathExp.evaluate(document, XPathConstants.NODESET);

我在这里检查是否 (nodeList.getLength()==0) 那么这意味着我没有任何传递了发布 ID 的节点。

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

在这一行中 newelement.getOwnerDocument().appendChild(newelement);其给出错误(org.w3c.dom.DOMException:HIERARCHY_REQUEST_ERR:试图在不允许的地方插入节点。)。

请推荐!!

【问题讨论】:

    标签: java xpath


    【解决方案1】:

    您当前正在对文档本身调用appendChild。这最终会创建多个根元素,这显然是你做不到的。

    您需要找到要添加节点的适当元素,并将其添加到该元素。例如,如果你想将新元素 添加到根元素,你可以使用:

    document.getDocumentElement().appendChild(newelement);
    

    【讨论】:

    • 非常有帮助的答案!!
    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多