SimpleXML:根据子元素的内容选择父节点



这应该是一件容易的事,但我只是没有让它工作: 在下面的代码片段中,我想选择具有值为"Categoryname2"的<Name>子节点的<WebFilterCategory>节点:

<?php
$xmlstring = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<Request>
<Login>
<UserName>admin</UserName>
<Password>admin</Password>
</Login>
<Set Operation="get">
<WebFilterCategory transactionid="">
<Name>Categoryname1</Name>
<Classification>Objectionable</Classification>
<DomainList>
<Domain>example1.com</Domain>
<Domain>example2.com</Domain>
</DomainList>
</WebFilterCategory>
<WebFilterCategory transactionid="">
<Name>Categoryname2</Name>
<Classification>Objectionable</Classification>
<DomainList>
<Domain>example1.org</Domain>
<Domain>example2.org</Domain>
</DomainList>
</WebFilterCategory>
</Set>
</Request>
XML;
$xml = simplexml_load_string( $xmlstring ) or die("Error: Cannot create object");
foreach ($xml->query('//WebFilterCategory/Name[contains(., "Categoryname2")]') as $category) {
print_r($xmlstring);
}
?>

可能,还有一个更精简的查询来获得所需的结果。

您要查找的方法不是query而是 xpath

然后,您可以更新路径以匹配名称包含Categoryname2

//WebFilterCategory[Name[contains(., "Categoryname2")]]' 

更新的代码

$xml = simplexml_load_string( $xmlstring ) or die("Error: Cannot create object");
foreach ($xml->xpath('//WebFilterCategory[Name[contains(., "Categoryname2")]]') as $category) {
print_r($category);
}

输出

SimpleXMLElement Object
(
[@attributes] => Array
(
[transactionid] => 
)
[Name] => Categoryname2
[Classification] => Objectionable
[DomainList] => SimpleXMLElement Object
(
[Domain] => Array
(
[0] => example3.org
[1] => example2.org
)
)
)

查看 Php 演示

最新更新