日期:2014-05-17 浏览次数:20655 次
[User:root Time:00:07:19 Path:/home/liangdong/php]$ php xpath.php
type:small
color:white
age:5
[User:root Time:00:07:19 Path:/home/liangdong/php]$ cat xpath.php
<?php
$str = <<<EOF
<?xml version="1.0" encoding="utf8" ?>
<pets>
<pet id="01">
<type resource="big"/>
<color resource="black"/>
<age resource="2"/>
</pet>
<pet id="02">
<type resource="small"/>
<color resource="white"/>
<age resource="5"/>
</pet>
</pets>
EOF;
$xml = simplexml_load_string($str, "SimpleXMLElement", LIBXML_NOBLANKS);
$res = $xml->xpath("/pets/pet[type[@resource='small'] and color[@resource='white'] and age[@resource='5']]");
foreach ($res as $node) {
$children = $node->children();
foreach ($children as $child) {
echo $child->getName() . ":" . $child['resource'] . PHP_EOL;
}
}
?>
------解决方案--------------------
$str = <<<EOF
<?xml version="1.0" encoding="utf8" ?>
<pets>
<pet id="01">
<type resource="big"/>
<color resource="black"/>
<age resource="2"/>
</pet>
<pet id="02">
<type resource="small"/>
<color resource="white"/>
<age resource="5"/>
</pet>
</pets>
EOF;
$xml = simplexml_load_string($str);
$res = $xml->xpath("/pets/pet[type[@resource='small'] and color[@resource='white'] and age[@resource='5']]");
echo $res[0]->attributes()->id; //02