我的record.xml看起来像:
<record>
<name>john</name>
<gender>male</gender>
<subject>mathematics, english, science</subject>
</record>
<record>
<name>jamie</name>
<gender>female</gender>
<subject>mathematics, science</subject>
</record>
<record>
<name>jamie</name>
<gender>female</gender>
<subject>social-science, english</subject>
</record>
我想编写一个xpath查询,它将返回包含一个或多个给定主题的记录节点。
例如:
如果想获得主题数学和科学
的学生的记录
然后应该返回第二条记录,即
<record>
<name>jamie</name>
<gender>female</gender>
<subject>mathematics, science</subject>
</record>
这就是我现在所做的:
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('record.xml');
$xpathvar = new Domxpath($xmldoc);
$res = $xpathvar->query('//record/subject[. = "science"]');
foreach($res as $data){
echo $data->textContent.'<br>';
}
?>
我想达到这样的结果:
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('record.xml');
$xpathvar = new Domxpath($xmldoc);
$res = $xpathvar->query('//record/subject[. = "science" and mathematics]');
foreach($res as $data){
echo $data->textContent.'<br>';
}
?>
答案 0 :(得分:1)
除非你可以将主题分成他们自己的节点,否则实际上不会有很好的方法来实现这一点。
/r/record[contains(subject,"science") and contains(subject,"mathematics") and ... ]
没有什么可以确定单词的分割位置,所以如果你有一个主题,比如说“计算机科学”那么你就会受到误击。你会更好,你可以将主题文本分成单独的元素。
<record>
<name>jamie</name>
<gender>female</gender>
<subject>mathematics</subject>
<subject>science</subject>
</record>
xpath = /r/record[subject[.="science" and .="mathematics" ... and ...] ]
或者像这样使用某种形式的分词分隔符:
<record>
<name>jamie</name>
<gender>female</gender>
<subject>|mathematics|science|</subject>
</record>
xpath = /r/record[contains(subject,"|science|") and contains(subject,"|mathematics|") and ... ]