아래의 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 : 허가되어 있지 않은 노드를 삽입하려고했습니다).
주세요.
매우 도움이 답! – prabu