如何使用java在文档中附加新节点
我有下面的updateFile代码,这里我试图在xml文件中没有publicationid的情况下添加新节点如何使用java在文档中附加新节点,java,xpath,Java,Xpath,我有下面的updateFile代码,这里我试图在xml文件中没有publicationid的情况下添加新节点 public static void UpdateFile(String path, String publicationID, String url) { try { File file = new File(path); if (file.exists()) { DocumentBuil
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)xpathxp.evaluate(文档,XPathConstants.NODESET)
这里我检查(nodeList.getLength()==0),这意味着我没有传递publicationid的节点
如果没有这样的节点,我想创建一个新节点
在此行中,newelement.getOwnerDocument().appendChild(newelement);它的给定错误(org.w3c.dom.DOMException:HIERARCHY\u REQUEST\u ERR:试图在不允许的位置插入节点)
请建议 您当前正在对文档本身调用
appendChild
。这将最终创建多个根元素,这显然是您无法做到的
您需要找到要添加节点的适当元素,并将其添加到该元素中。例如,如果要将新元素添加到根元素,可以使用:
document.getDocumentElement().appendChild(newelement);
非常有用的答案!!