ant ant - 5 months ago 7
Java Question

How can I insert element into xml after/before certain element in java

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 :

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

Answer

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

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