Ars
Ars

Reputation: 282

get xml node child element value based on the parent attribute value

I've one xml like:-

 <SkillMap>
   <ExitPoint ID="01">
    <NodeName>abcd</NodeName>
   </ExitPoint>
   <ExitPoint ID="04">
    <NodeName>defg</NodeName>
   </ExitPoint>
   <ExitPoint ID="22">
    <NodeName>mnop</NodeName>
   </ExitPoint>
  </SkillMap>

I am trying to get the value of the <ExitPoint> node based on the ID value i.e. if i enter the ID as 01 it should give "abcd" and if 22 it should give "mnop" and so on, but i'm not getting it, tried lot, please help.

Thanks, Ars

Upvotes: 0

Views: 1111

Answers (1)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78639

You can do it using Xpath, consider the following example taken from the JAXP Specification 1.4 (which I recommend you to consult for this):

// parse the XML as a W3C Document
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
org.w3c.Document document = builder.parse(new File("/widgets.xml"));
// evaluate the XPath expression against the Document
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/widgets/widget[@name='a']/@quantity";
Double quantity = (Double) xpath.evaluate(expression, document, XPathConstants.NUMBER);

Upvotes: 1

Related Questions