为什么我的XPath什么都没选?

时间:2016-07-22 04:09:02

标签: java xml xpath xml-parsing

我的XML文件

<classifications>
  <classification sequence="1">
    <classification-scheme office="" scheme="CS" />
    <section>G</section>
    <class>01</class>
    <subclass>R</subclass>
    <main-group>33</main-group>
    <subgroup>365</subgroup>
    <classification-value>I</classification-value>
  </classification>
  <classification sequence="2">
    <classification-scheme office="" scheme="CS" />
    <section>G</section>
    <class>01</class>
    <subclass>R</subclass>
    <main-group>33</main-group>
    <subgroup>3415</subgroup>
    <classification-value>A</classification-value>
  </classification>
  <classification sequence="1">
    <classification-scheme office="US" scheme="UC" />
    <classification-symbol>324/300</classification-symbol>
  </classification>
  <classification sequence="2">
    <classification-scheme office="US" scheme="UC" />
    <classification-symbol>324/307</classification-symbol>
  </classification>          
</classifications>

我想用以下条件解析值 需要所有classification-symbol元素值以及条件office="US"

我尝试了下面的XPath,

NodeList usClassification = (NodeList)xPath.compile("//classifications//classification//classification-scheme[@office=\"US\"]//classification-symbol//text()").evaluate(xmlDocument, XPathConstants.NODESET);

但是我得到一个空的结果集,

System.out.println(usClassification.getLength()); //its becomes zero

2 个答案:

答案 0 :(得分:3)

classification-symbol不是classification-scheme的孩子 - 他们是兄弟姐妹。使用following-sibling轴从“scheme”变为“symbol”:

//classifications/classification/classification-scheme[@office=\"US\"]/following-sibling::classification-symbol/text()

答案 1 :(得分:3)

这个XPath(写在两行以方便可读性),

/classifications/classification[classification-scheme/@office='US']
                /classification-symbol/text()

将选择classification-symbol元素的classification文字,classification-scheme @office属性值等于US

324/300
324/307

按要求。