Search code examples
javaxmlnodesgetelementsbytagnamenodelist

getting a specific XML tag element in Java


I have the following XML:

<oa:Parties>
  <ow-o:SupplierParty>
    <oa:PartyId>
      <oa:Id>1</oa:Id>
    </oa:PartyId>
  </ow-o:SupplierParty>
  <ow-o:CustomerParty>
    <oa:PartyId>
      <oa:Id>123-123</oa:Id> // I NEED THIS
    </oa:PartyId>
    <oa:Business>
      <oa:Id>ShiptoID</oa:Id>
    </oa:Business>
  </ow-o:CustomerParty>
</oa:Parties>

How can I get the 123-123 value?

I tried this:

NodeList nodeList = document.getElementsByTagName("ow-o:CustomerParty");
Node parentNode = nodeList.item(0);
String ID = parentNode.getTextContent();

But it has both <oa:Id> elements.

Is there a way to find the value based on hierarchy ow-o:CustomerParty > oa:PartyId > oa:Id?


Solution

  • I’d just go with A simple filter on its child items. This way

    NodeList nodeList = document.getElementsByTagName("ow-o:CustomerParty");
    Node parentNode = nodeList.item(0);
    
    Node partyNode = filterNodeListByName(parentNode.getChildNodes(), "oa:PartyId");
    
    Node idNode = null;
    if(partyNode!=null)
        idNode = filterNodeListByName(partyNode.getChildNodes(), "oa:Id")
    
    String ID = idNode!=null ? idNode.getTextContent() : "";
    

    Basically the first filter gets all the child items matching the node name "oa:PartiId". It then maps the found node (I used findAny but findFirst could still be a viable option in your case) to the child item node's, with name oa:id, text content

    SN: I’m considering you’ll define a method such so

    public boolean isNodeAndWithName(Node node, String expectedName) {
        return node.getNodeType() == Node.ELEMENT_NODE && expectedName.equals(node.getNodeName());
    }
    

    And this is the additional method

    public Node filterNodeListByName(NodeList nodeList, String nodeName) {
            for(int i = 0; i<nodeList.getLength(); i++)
                if(isNodeAndWithName(nodeList.item(i), nodeName)
                    return nodeList.item(i);
            return null;
    }