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

时间:2010-07-14 15:12:03

标签: java xml dom xpath

这是我的代码,也许你会马上注意到我缺少的东西:

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现有节点之前插入新节点(<newNode>value</newNode>)。这是我的XML示例文件:

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

2 个答案:

答案 0 :(得分:30)

这是我刚刚使用您提供的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);

答案 1 :(得分:6)

我想你想插入父母而不是孩子:

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