I have an XML but all I know is the name of the element I want to find the value of. That is, I can't use XPath to easily retrieve the element. I have to recursively work my way through the XML which I seem to fail. What I've tried is:
Assume an XML of the following structure:
<Store id="1">
...
<Customer>
<CustomerId>123</CustomerId>
</Customer>
</Store>
I want to get the value of the CustomerId tag. In reality, I don't know where in the XML my CustomerId tag is. I tried the following recursion:
private String parseXmlForCustomerId(Element element) {
if (element.getNodeName().equals("CustomerId")) {
return element.getTextContent();
}
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE && parseXmlForCustomerId((Element) node).equals("CustomerId")) {
return node.getTextContent();
}
}
return "";
}
What have I done wrong?
Thanks in advance!
//CustomerIdseems fine.