Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java DOM xml cant get child

My XML looks like this:

<ConnProf ConnProfID="1111">
  <ConnNum>1</ConnNum>
  <IsMSPA>false</IsMSPA>
  <IsArray>false</IsArray>
  <IsDDOR>false</IsDDOR>

  <Subsystem SSID="2222"ConnProfID="3333">
    <SSName>AA</SSName>
    <GenericSSName>AA</GenericSSName>
    <ConnFuncAddr>aaa</ConnFuncAddr>
    <DSSNum>22</DSSNum>
    <isRemoved>false</isRemoved>
  </Subsystem>

  <Subsystem SSID="4444" ConnProfID="5555">
    <SSName>BBBB</SSName>
    <GenericSSName>BB</GenericSSName>
    <ConnFuncAddr>bbbbbb</ConnFuncAddr>
    <DSSNum>44</DSSNum>
    <isRemoved>false</isRemoved>
  </Subsystem>

I am having trouble getting ConnNum, IsMSPA, IsArray, and IsDDOR. I tried getting ConnNum with:

//get ConnNum
                Node n = doc.getFirstChild();
                if (n.hasChildNodes())
                    System.out.println(n.getFirstChild().getNodeValue());
                else 
                    System.out.println(n.getNodeValue());

but it just returns null when im expecting 1.

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class test 
{
    public static void main(String[] args)
    {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try 
        {
            DocumentBuilder db = dbf.newDocumentBuilder();

            for (int i = 1; i <= 8; i++)
            {
                Document doc = db.parse("file" + i + ".xml");

                doc.getDocumentElement ().normalize ();
                System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());

                //get ConnNum
                Node n = doc.getFirstChild();
                if (n.hasChildNodes())
                    System.out.println(n.getFirstChild().getNodeValue());
                else 
                    System.out.println(n.getNodeValue());

                NodeList listOfSubsystems = doc.getElementsByTagName("Subsystem");
                int totalSubsystems = listOfSubsystems.getLength();

                if (totalSubsystems == 0)
                    continue;
                else
                {
                    System.out.println("Total number of subsystems : " + totalSubsystems + "\n");

                    Dish dish = new Dish();

                    for(int s=0; s < listOfSubsystems.getLength() ; s++)
                    {
                        Node firstPersonNode = listOfSubsystems.item(s);

                        if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE)
                        {
                            Element firstPersonElement = (Element)firstPersonNode;

                            printElement(firstPersonElement, "SSName");
                            printElement(firstPersonElement, "GenericSSName");
                            printElement(firstPersonElement, "ConnFuncAddr");
                            printElement(firstPersonElement, "DSSNum");
                            printElement(firstPersonElement, "SCNum");
                            printElement(firstPersonElement, "SCAcronym");
                            printElement(firstPersonElement, "PassNum");
                            printElement(firstPersonElement, "FzCode");
                            printElement(firstPersonElement, "isRemoved");
                            System.out.println("------------------");
                        }
                    }
                    System.out.println("\n==============================");
                }

            }
        }
        catch(ParserConfigurationException pce) 
        {
            pce.printStackTrace();
        }
        catch(SAXException se) 
        {
            se.printStackTrace();
        }
        catch(IOException ioe) 
        {
            ioe.printStackTrace();
        }
    }   

    public static void printElement(Element a, String name)
    {
        NodeList elementList = a.getElementsByTagName(name);
        Element b = (Element)elementList.item(0);

        if (b != null)
        {
            NodeList list = b.getChildNodes();
            System.out.println( ((Node)list.item(0)).getNodeValue().trim() );
        }
    }
}
like image 561
Raptrex Avatar asked Jun 22 '11 18:06

Raptrex


Video Answer


3 Answers

Perhaps the first child is not what you think it is. Whitespace is important in XML and it is possible that the firstChild is actually a text node.

Nodes have a type and you can iterate all the children checking for Element node type to get a handle to the actual elements.

Edit: This prints the values you are after. It is filtering on Element nodes and then the first child node (the one containing the text) of each.

NodeList nodeList = n.getChildNodes();
for (int j = 0; j < nodeList.getLength(); j++) {
    Node childNode = nodeList.item(j);
    if (childNode.getNodeType() == Node.ELEMENT_NODE) {
        System.out.println(childNode.getNodeName() + " " + childNode.getFirstChild().getNodeValue());
    }
}

Also, as @Steve Townsend correctly writes, you could use getTextContent() instead of childNode.getFirstChild().getNodeValue() if you are using Java 1.5 or above.

like image 92
andyb Avatar answered Sep 19 '22 03:09

andyb


 NodeList nodeList = n.getChildNodes();
 for (int j = 0; j < nodeList.getLength(); j++) {
     Node childNode = nodeList.item(j);
     if (childNode instanceof Element) {
          Element childElement = (Element) childNode;
          System.out.println(childElement.getNodeName() + " " +     childElement.getFirstChild().getNodeValue());
      }
  }   
like image 26
iKushal Avatar answered Sep 18 '22 03:09

iKushal


You need to use getTextContent() here. You can use getNodeName() first (in debug version only) to ensure you are in the correct place.

getNodeValue() returns null if the node in hand is an element. There's a table here that describes the results of getNode* in each possible context.

like image 21
Steve Townsend Avatar answered Sep 20 '22 03:09

Steve Townsend