2012-05-28 4 views
4

아래의 updateFile 코드가 있습니다. xml 파일에 publicationid가 없을 때 새 노드를 추가하려고합니다. I하여 XPathExpression는 모든 검색된 노드를 사용하고 위의 코드에서자바를 사용하여 문서에 새 노드를 추가하는 방법

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

는 NodeList의 노드 목록에 추가 = (NodeList의) 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

관련 문제