0

I am trying to assign a value to an empty XML node but it doesn't seem to be working. My XML structure is as so:

<createCustomer>
    <customerAttributes>
        <firstName></firstName>
        <lastName></lastName>
    </customerAttributes>
</createCustomer>

I am trying to assign a first name and surname in the following code:

private void createXML(Document skeleton, Map params) {
skeleton.getDocumentElement().normalize();

NodeList customerNodes = skeleton.getElementsByTagName("customerAttributes");

            for(int i=0; i<customerNodes.getLength(); i++) {
                NodeList children = customerNodes.item(i).getChildNodes();
                    for(int j=0; j<children.getLength(); j++) {
                        String childNode = children.item(j).getNodeName();
                            if(childNode.equalsIgnoreCase("firstName")){
                                children.item(j).setNodeValue(String.valueOf(params.get("fname")));
                                System.out.println(children.item(j));
                            }
                            else if (childNode.equalsIgnoreCase("lastName")){
                                children.item(j).setNodeValue(String.valueOf(params.get("sname")));
                                System.out.println(children.item(j));
                            }
                    }  
             }

     }
}

The output of the print statements are:

firstname: null surname: null

but I know for certain that the values in the map are correct because print statements output the expected map values. Also, if I replace the params.get("string") with a hardcoded string, I still get the output: firstname: null. The code is not throwing any exceptions. I've also tried setTextContent but this doesn't work either

2
  • check that you pasted the correct code snippet; the outer loop seems duplicated; also, pasting the exception you get, if any, is useful Commented Dec 19, 2013 at 12:54
  • @guido thanks I've formatted the code to be easier to read. The code is not giving any exceptions it builds and runs ok Commented Dec 19, 2013 at 12:59

1 Answer 1

2

You can use setTextContent(String):

NodeList customerNodes = skeleton.getElementsByTagName("customerAttributes");
for (int i = 0; i < customerNodes.getLength(); i++) {
    NodeList children = customerNodes.item(i).getChildNodes();
    for (int j = 0; j < children.getLength(); j++) {
        String childNode = children.item(j).getNodeName();
        if (childNode.equalsIgnoreCase("firstName")) {
            children.item(j).setTextContent(String.valueOf(params.get("fname")));
        }
        else if (childNode.equalsIgnoreCase("lastName")) {
            children.item(j).setTextContent(String.valueOf(params.get("sname")));
        }
    }  
}

Edit:

It works, here is a full example showing the result.

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

public class Foo {
    public static void main(String[] args) throws Exception {
        // --------- LOAD XML
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader("<createCustomer>\r\n" + 
                "    <customerAttributes>\r\n" + 
                "        <firstName></firstName>\r\n" + 
                "        <lastName></lastName>\r\n" + 
                "    </customerAttributes>\r\n" + 
                "</createCustomer>")));

        // --------- PROCESS
        NodeList customerNodes = doc.getElementsByTagName("customerAttributes");

        for (int i = 0; i < customerNodes.getLength(); i++) {
            NodeList children = customerNodes.item(i).getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
                String childNode = children.item(j).getNodeName();
                if (childNode.equalsIgnoreCase("firstName")) {
                    children.item(j).setTextContent(String.valueOf("John"));
                }
                else if (childNode.equalsIgnoreCase("lastName")) {
                    children.item(j).setTextContent(String.valueOf("Doe"));
                }
            }  
        }

        // --------- OUTPUT
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        System.out.println(writer.getBuffer().toString());
    }
}

It does output:

<createCustomer>
    <customerAttributes>
        <firstName>John</firstName>
        <lastName>Doe</lastName>
    </customerAttributes>
</createCustomer>
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry I already tried that and it didn't work either. Will update my question. Thanks for your answer
funny but it still doesn't work for me! I'm reading the XML from a file into a document object then parsing the XML directly from there. That shouldn't really matter though
My print statements were wrong. Doh! I should have put in System.out.print(children.item(j).getTextContent()); Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.