Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving different child elements xml

Tags:

java

dom

xml

I have a xml file that looks like this.

<Device>
<Staff>
<Name>ABC</Name>
<Name>Hello</Name>
</Staff>
<Connect>
<Speed>123</Speed>
<Speed>456</Speed>
</Connect>
</Device>

I need help in retrieving the value of name & speed as i have never tried xml before. I am getting null pointer exception whenever I try to retrieve the element values. Any help is appreciated.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();

      // Load the input XML document, parse it and return an instance of the
      // Document class.
      Document document = builder.parse(new File("C:/Users/AA/Desktop/eclipse/lol/testing.xml"));//change to own directory


      NodeList nodeList = document.getDocumentElement().getChildNodes();
      System.out.println(nodeList.getLength());
     for (int i = 0; i < nodeList.getLength(); i++) {
           Node node = nodeList.item(i);

           if (node.getNodeType() == Node.ELEMENT_NODE) {
               System.out.println(i);
                Element elem = (Element) node;

                // Get the value of the ID attribute.
             //   String ID = node.getAttributes().getNamedItem("ID").getNodeValue();

                // Get the value of all sub-elements.
                String name = elem.getElementsByTagName("Name")
                                    .item(0).getChildNodes().item(0).getNodeValue();

               Integer speed = Integer.parseInt(elem.getElementsByTagName("Connect")
                        .item(0).getChildNodes().item(0).getNodeValue());//null pointer exception happens here

                staffList.add(new staff(name));
                connectList.add(new connect(speed));
           }
      }

      // Print all employees.
      for (staff stl : staffList)
           {System.out.println("STAFF "+stl.getName());}
      for (connect ctl : connectList)
      {System.out.println("Connect "+ctl.getSpeed());}
like image 729
Wayne Avatar asked Jul 12 '26 12:07

Wayne


1 Answers

You will have null pointer exceptions because you're assuming that in every iteration of the for loop, the desired nodes have children elements:

String name = elem.getElementsByTagName("Name")
                                .item(0).getChildNodes().item(0).getNodeValue();

In the above code, you are accessing the first child of a Name element which is a text node (e.g. ABC), and then getting its children nodes, which will cause an exception since there no children elements inside the text node.

Likewise,

Integer speed = Integer.parseInt(elem.getElementsByTagName("Connect")
                    .item(0).getChildNodes().item(0).getNodeValue());

will cause an exception in one of the iterations of the loop where elem corresponds to Connect itself.

You can try the following code instead:

if (node.getNodeType() == Node.ELEMENT_NODE) {
    System.out.println(i);
    Element elem = (Element) node;

    // Get the value of the ID attribute.
    // String ID =
    // node.getAttributes().getNamedItem("ID").getNodeValue();

    // Get the value of all sub-elements.
    NodeList nameNodes = elem.getElementsByTagName("Name");
    for(int j = 0; j < nameNodes.getLength(); j++) {
        Node nameNode = nameNodes.item(j);
        staffList.add(new staff(nameNode.getTextContent()));
    }

    NodeList speedNodes = elem.getElementsByTagName("Speed");
    for(int j = 0; j < speedNodes.getLength(); j++) {
        Node speedNode = speedNodes.item(j);
        connectList.add(new connect(Integer.parseInt(speedNode.getTextContent())));
    }
}

P.S.: Try to use class names that start with an uppercase.

like image 176
M A Avatar answered Jul 14 '26 00:07

M A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!