如何在java中的某个元素之后/之前将元素插入到xml中
这是我的代码,也许你会马上注意到我错过了什么:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(fileName));
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//CustomerId");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
Nodelist nodes = (NodeList) result;
Text a = doc.createTextNode("value");
Element p = doc.createElement("newNode");
p.appendChild(a);
for (int i = 0; i < nodes.getLength(); i++) {
nodes.item(i).insertBefore(p, nodes.item(i));
}
我正在尝试在 CustomerId 现有节点之前插入新 node()。这是我的XML示例文件:<newNode>value</newNode>
<Customer>
<names>
<firstName>fName</firstName>
<lastName>lName</lastName>
<middleName>nName</middleName>
<nickName/>
</names>
<addressList>
<address>
<streetInfo>
<houseNumber>22</houseNumber>
<baseName>Street base name</baseName>
<district>kewl district</district>
</streetInfo>
<zipcode>22231</zipcode>
<state>xxx</state>
<country>xxxz</country>
<primary>true</primary>
</address>
</addressList>
<CustomerId/>
<SSN>561381</SSN>
<phone>
<homePhone>123123123</homePhone>
<officePhone/>
<homePhone>21319414</homePhone>
</phone>
<preferred>true</preferred>
</Customer>
这是一个被抛出的异常,我只是不知道还能尝试什么:
NOT_FOUND_ERR:尝试在不存在节点的上下文中引用节点。