0

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?

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the response. I tried this solution but looks like NodeList does not have stream(). I am getting an error error: cannot find symbol: method stream() location: interface NodeList
My bad I'm used to a library which gave you the list I'm gonna fix it right away
@AJ let me know, this is adapted to default NodeList object
Thank you, it worked! Just wanted to point out in case someone else comes across it, the method is getChildNodes(), not getChildItems(). And the isNodeWithName method name does not match, so you can edit your question if you like with those changes. Thanks again!
Thanks my bad, copying the code I lost some parts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.