我有以下 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) 那么这意味着我没有任何传递了 publicationid 的节点。
如果没有这样的节点,我想创建一个新节点。
在这一行中 newelement.getOwnerDocument().appendChild(newelement); 其给出错误(org.w3c.dom.DOMException:HIERARCHY_REQUEST_ERR:尝试插入不允许的节点。)。
请推荐!!