如何在java中的某個元素之后之前將元素插入到xml中 - How can I insert element into xml afterbefore certain element in java -开发者知识库

如何在java中的某個元素之后之前將元素插入到xml中 - How can I insert element into xml afterbefore certain element in java -开发者知识库,第1张

Here is my code, maybe you will notice right away what I'm missing :

這是我的代碼,也許你會馬上注意到我缺少的東西:

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));
}

I'm trying to insert new node(<newNode>value</newNode>) before CustomerId existing node. Here is my XML sample file :

我正在嘗試在CustomerId現有節點之前插入新節點( value )。這是我的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>

This is an exception getting thrown I just don't know what else to try :

這是一個拋出的異常我只是不知道還有什么可以嘗試:

NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.

NOT_FOUND_ERR:嘗試在不存在的上下文中引用節點。

2 个解决方案

#1


28  

Here an example I just tested using the xml sample you provided.

這里是我剛剛使用您提供的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));

Here is the result:

結果如下:

<?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>

If you're interested, here's the sample code I used to show the result:

如果您有興趣,這是我用來顯示結果的示例代碼:

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);

最佳答案:

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复