根据父属性值获取xml节点子元素值

时间:2012-06-08 17:11:56

标签: java xml-parsing

我有一个xml,如: -

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

我试图根据ID值获取<ExitPoint>节点的值,即如果我输入ID为01则应该给出&#34; abcd&#34;如果22它应该给&#34; mnop&#34;等等,但我没有得到它,尝试了很多,请帮忙。

谢谢, ARS

1 个答案:

答案 0 :(得分:1)

您可以使用Xpath执行此操作,请考虑以下从JAXP Specification 1.4获取的示例(我建议您参考此示例):

// 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);