David Silva
David Silva

Reputation: 2017

DOM XML - How to get child node?

I have xml like this:

<param>
  <name>some_list</name>
  <value>
    <items>
      <item>
        <value>7</value>
        <type>Long</type>
      </item>
      <item>
        <value>23</value>
        <type>String</type>
      </item>
      <item>
        <value>1.0</value>
        <type>Double</type>
      </item>
      <item>
        <value>true</value>
        <type>Boolean</type>
      </item>
      <item>
        <value>13-01-2014 16:03:50</value>
        <type>Date</type>
      </item>
      <item>
        <value>[7, false]</value>
        <type>String</type>
      </item>
    </items>
  </value>
  <type>Collection</type>
</param>

I need to get value of type node - child od param node (in this case 'Collection'). I am not interested children of item nodes, so solution like this:

NodeList nodes = element.getElementsByTagName("type").item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();

is wrong (it returns 'Long', not 'Collection'!)

Upvotes: 0

Views: 1082

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503409

getElementsByTagName returns all descendant elements. You just want all immediate child elements.

You can use getChildNodes() and then filter them if you want. For example:

NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
    Node node = children.item(i);
    if (node.getNodeType() == Node.ELEMENT_TYPE
        && node.getLocalName().equals("type")) {
        // Use the node, get its value etc
    }
}

You might want to look at using XPath or an alternative Java XML API (e.g. JDOM) to make this simpler, too. If you do the above a lot, you probably want to extract it to a helper method to return all the direct children with a particular element name (or just the first one).

Upvotes: 1

Related Questions