【问题标题】:get xml node child element value based on the parent attribute value根据父属性值获取xml节点子元素值
【发布时间】:2012-06-08 17:11:55
【问题描述】:

我有一个类似的 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 值获取 &lt;ExitPoint&gt; 节点的值,即如果我输入 ID 为 01,它应该给出“abcd”,如果输入 22,它应该给出“mnop”等等,但我不明白,试了很多次,请帮忙。

谢谢, 阿尔斯

【问题讨论】:

  • 你应该为此使用 Xpath。
  • 到目前为止您尝试过什么?你遇到过什么问题吗?

标签: java xml-parsing


【解决方案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);

【讨论】:

  • 谢谢,但对于上述 xml,我是否必须使用 String expression = "/ExitPoint/widget[@name='ID']/@quantity"; 或 wat?
  • 我认为,如果您阅读了我在回答中分享的材料,您最终将能够弄清楚自己。我认为这就是应该的方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2021-05-17
  • 2018-04-13
相关资源
最近更新 更多