Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating a NodeList consisting some tags with same name using DOM

I'm trying to read in an XML using DOM in Java

<?xml version="1.0"?>
<record>
<user>
    <name>Leo</name>
    <email>****@****.com</email>
        <food-list>
            <food>Hamburgers</food>
            <food>Fish</food>
        </food-list>
</user>
</record>

My current solution is

    for (int userNumber = 0; userNumber < masterList.getLength(); userNumber++) {

           Node singleUserEntry = masterList.item(userNumber);
           if (singleUserEntry.getNodeType() == Node.ELEMENT_NODE) {

              org.w3c.dom.Element userEntryElement = (org.w3c.dom.Element) singleUserEntry;



              System.out.println("name : " + getTagValue("name", userEntryElement));
              System.out.println("email : " +getTagValue("email", userEntryElement));
              NodeList foodList = userEntryElement.getElementsByTagName("food-list").item(0).getChildNodes();
              for(int i = 0; i < foodList.getLength(); i++){
                  Node foodNode = foodList.item(i);
                  System.out.println("food : " + foodNode.getNodeValue());
              }

private static String getTagValue(String sTag, org.w3c.dom.Element eElement) {
     NodeList nlList =  eElement.getElementsByTagName(sTag).item(0).getChildNodes();
     Node nValue = (Node) nlList.item(0);
     return nValue.getNodeValue();

And the output now is

name : Leo 
email : ******@*****.com
food :          
food : null
food :          
food : null
food : 

Which quite confuses me. Could you tell me where I'm wrong? The number of food tags is not pre-defined.

like image 939
YankeeWhiskey Avatar asked Aug 26 '12 18:08

YankeeWhiskey


1 Answers

((Node) foodNode.getChildNodes().item(0)).getNodeValue()

Note that, as you can clearly see, dealing with the DOM API in Java is pretty painful. Have you looked at JDOM or dom4j?

like image 200
obataku Avatar answered Oct 10 '22 09:10

obataku