使用 SimpleXMLElement :: xpath 检查特定节点值
以下解决方案使用 tag="100"
查找数据字段,并使用 code="a"
获取子字段的值。现在我意识到我还需要检查是否存在 code="4"
的子字段,如果存在,则检查该值是否为 xyz 并仅获取子字段 code="a" value 如果条件为真。我如何更改代码才能做到这一点?
XML:
<datafield tag="100">
<subfield code="a">value
</subfield>
<subfield code="4">xyz
</subfield>
</datafield>
代码
if($datafield['tag']=='100'){
$datafield->registerXPathNamespace('foo', 'http://www.loc.gov/MARC21/slim');
foreach( $datafield->xpath('foo:subfield') as $sf ) {
if($sf['code']=='a'){
$auth=func($sf);
}
}
}
The following solution finds the datafield with tag="100"
and get the value of subfield with code="a"
. Now I realised that I also need to check if a subfield with code="4"
exist and if so check if the value is xyz and only fetch the subfield code="a"
value if that condition is true. How can I change the code in order to do that?
XML:
<datafield tag="100">
<subfield code="a">value
</subfield>
<subfield code="4">xyz
</subfield>
</datafield>
code
if($datafield['tag']=='100'){
$datafield->registerXPathNamespace('foo', 'http://www.loc.gov/MARC21/slim');
foreach( $datafield->xpath('foo:subfield') as $sf ) {
if($sf['code']=='a'){
$auth=func($sf);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用:
或使用:
上面的第一个 XPath 表达式选择顶部元素的所有
subfield
子级的所有文本节点子级,这些子级的值是code
属性为"a"
,但前提是顶部元素有一个subfield
子元素,其code
属性具有该值4
删除前导和尾随空白字符后的字符串值为"xyz"
第二个表达式非常相似,但它直接计算第一个的字符串值第一个表达式选择的文本节点。
这些表达式比其他答案中的表达式更简单,因为根本不使用反向轴,并且所有谓词都在最合适的位置指定。
Use:
Or use:
The first XPath expression above selects all text nodes children of all
subfield
children of the top element for which the value of theircode
attribute is"a"
but only if the top element has asubfield
child whosecode
attribute has the value4
and whose string value after removing the leading and trailing whitespace characters is"xyz"
The second expression is very similar, but it directly evaluates to the string value of the first of the text nodes that are selected by the first expression.
These expressions are simpler than the ones in other answers, because no reverse axis is used at all and all predicates are specified at their most appropriate place.
如果所有条件都适用,则使用 xpath 直接获取所需节点
/datafield[@tag='100']/subfield[@code='a'][normalize-space(../subfield[@code=' 4']) = 'xyz']
Use xpath to directly fetch the desired node, if all conditions apply
/datafield[@tag='100']/subfield[@code='a'][normalize-space(../subfield[@code='4']) = 'xyz']