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

Posted

技术标签:

【中文标题】java - 如何在java中的某个元素之后/之前将元素插入xml【英文标题】:How can I insert element into xml after/before certain element in java 【发布时间】:2011-03-15 22:10:51 【问题描述】:

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

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 现有节点之前插入新节点(&lt;newNode&gt;value&lt;/newNode&gt;)。这是我的 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:尝试 在上下文中引用节点 不存在。

【问题讨论】:

【参考方案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));

【讨论】:

以上是关于java - 如何在java中的某个元素之后/之前将元素插入xml的主要内容,如果未能解决你的问题,请参考以下文章

java如何删除掉数组中的某个元素??

java如何删除掉数组中的某个元素??

java如何获得集合里面某个元素的下标

java截取某个字符之前或者之后的字符串

Java字符串截取,截取某个字符之前或者之后的字符串

java怎么得到指定字符之后的字符串