4

I have below updateFile code, here I am trying to add new node when there is no publicationid 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 above code I am using XPathExpression and all the matched node are added in NodeList nodeList = (NodeList)xpathExp.evaluate(document, XPathConstants.NODESET);

Here I am checking if (nodeList.getLength()==0) then that means I don't have any node with the publicationid passed.

And if there is no node as such I want to create a new node.

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. ).

Please suggest!!

4

1 に答える 1

6

appendChild現在、ドキュメント自体を呼び出しています。それは複数のルート要素を作成することになりますが、これは明らかにできません。

ノードを追加する適切な要素を見つけて、それに追加する必要があります。たとえば、新しい要素ルート要素に追加する場合は、次のように使用できます。

document.getDocumentElement().appendChild(newelement);
于 2012-05-28T18:46:25.610 に答える