我有一个这样的 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT family (person)+>
<!ELEMENT person (name) >
<!ATTLIST person idnum ID #REQUIRED
gender (male | female) #REQUIRED
father IDREF #IMPLIED
mother IDREF #IMPLIED
children IDREFS #IMPLIED >
<!ELEMENT name (#PCDATA)>
<?xml version="1.0"?>
<!DOCTYPE family SYSTEM "family.dtd">
<family>
<person idnum = "T11" gender = "male" children ="T13 T14 T15"><name>11</name></person>
<person idnum = "T12" gender = "female" children ="T13 T14 T15"><name>12</name></person>
<person idnum = "T13" gender = "male" father="T11" mother="T12"><name>13</name></person>
<person idnum = "T14" gender = "male" father="T11" mother="T12"><name>14</name></person>
<person idnum = "T15" gender = "female" father="T11" mother="T12" children="T33"><name>15</name></person>
<person idnum = "T21" gender = "male" children="T23"><name>21</name></person>
<person idnum = "T22" gender = "female" children="T23"><name>22</name></person>
<person idnum = "T23" gender = "male" father="T21" mother="T22" children="T33"><name>23</name></person>
<person idnum = "T33" gender = "female" father="T23" mother="T15"><name>33</name></person>
</family>
我想检查查询:
所有没有 child 的人(包括
男性
和女性
)所有没有男孩的人(即
儿子
)
我试过了:
/family/person[count(children)==0]
/family/person[count(children)==0 and children!=male]
但它不起作用。
你能解释一下吗?谢谢。
最佳答案
XPath 中的等号运算符是“=”,而不是“==”。
写 children!=male 大概是一厢情愿的想法,我希望你真的没有想到这会奏效。
可能没有 child 的人可以通过没有@children 属性或属性存在但为空来表示。您可以通过测试 /family/person[normalize-space(@children)='']
第二个查询比较难,因为它涉及到连接。 XPath 1.0 无法处理每个连接查询; XPath 2.0 可以。你不说你正在使用哪个。另一个复杂问题是 id() 函数可能有点不稳定:处理管道并不总是保留有关哪些属性是 ID 的信息。但假设 id() 在您的环境中有效,您可以执行第二个查询(在 XPath 1.0 或 2.0 中)
/family/person[not(id(@children)[@gender='male'])]
关于java - XPath 表达式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10734222/