如何在java中的某个元素之后/之前将元素插入到xml中

2022-09-03 04:17:47

这是我的代码,也许你会马上注意到我错过了什么:

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:尝试在不存在节点的上下文中引用节点。


答案 1

下面是我刚刚使用您提供的 xml 示例进行测试的示例。

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder(); 
Document doc = builder.parse(new File("XmlTest.xml")); 

NodeList nodes = doc.getElementsByTagName("CustomerId");

Text a = doc.createTextNode("value"); 
Element p = doc.createElement("newNode"); 
p.appendChild(a); 

nodes.item(0).getParentNode().insertBefore(p, nodes.item(0));

结果如下:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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>
    <newNode>value</newNode>
<CustomerId/>
    <SSN>561381</SSN>
    <phone>
        <homePhone>123123123</homePhone>
        <officePhone/>
        <homePhone>21319414</homePhone>
        </phone>
    <preferred>true</preferred>
</Customer>

如果您有兴趣,以下是我用于显示结果的示例代码:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);

String xmlOutput = result.getWriter().toString();
System.out.println(xmlOutput);

答案 2

我认为你想插入到父级,而不是子级:

nodes.item(i).getParentNode().insertBefore(p, nodes.item(i));