检查xml节点的父节点是否具有特定属性

时间:2015-11-05 12:36:54

标签: php xml xpath

我有以下示例xml文件:

<?xml version="1.0" encoding="utf-8" ?>
<categories>
    <category id="1" name="Car">
        <category id="12" name="Electrical">
            <category id="18" name="On-Road">
                <category id="127" name="Carisma"></category>
                <category id="128" name="HPI - Maverick"></category>
                <category id="452" name="HSP"></category>
                <category id="130" name="Other"></category>
            </category>
            <category id="16" name="Off-Road">
                <category id="132" name="HPI - Maverick"></category>
                <category id="225" name="Carisma"></category>
                <category id="315" name="HSP"></category>
                <category id="420" name="Other"></category>
            </category>
        </category>
    </category>
</categories>

我需要的是具有特定值的任何子节点的所有父节点。

例如,如果id值为128, 然后它会回应:汽车/电气/路上/ HPI - Maverick

如果id值为12,则它将回显 Car / Electrical

继续......

我已设法获取具有特定id值的节点(如下),但我无法弄清楚如何从所选节点获取父链。

<?php
$file = "http://www.localhost.com/categories.xml";

$microline = new SimpleXMLElement($file, null, true);

foreach($microline as $cat){
    if ($cat->children['id'] = $catid) {

        $current_cat_name = $cat->xpath("//*[@id=$catid]/@name")[0];
        echo $current_cat_name;
    }
}
unset($microline);
?>

1 个答案:

答案 0 :(得分:0)

如果您使用XPath //*[@id=$catid]/ancestor-or-self::category/@name,那么您拥有所有属性值,只需要将它们与PHP中的斜杠字符连接起来。

这样做,例如

$xml = <<<'EOB'
<categories>
    <category id="1" name="Car">
        <category id="12" name="Electrical">
            <category id="18" name="On-Road">
                <category id="127" name="Carisma"></category>
                <category id="128" name="HPI - Maverick"></category>
                <category id="452" name="HSP"></category>
                <category id="130" name="Other"></category>
            </category>
            <category id="16" name="Off-Road">
                <category id="132" name="HPI - Maverick"></category>
                <category id="225" name="Carisma"></category>
                <category id="315" name="HSP"></category>
                <category id="420" name="Other"></category>
            </category>
        </category>
    </category>
</categories>
EOB;

$root = new SimpleXMLElement($xml);
$id = 127;
$cats = $root->xpath("//*[@id=$id]/ancestor-or-self::category");

$path = implode('/', array_map(function($a) { return $a['name']; }, $cats));

echo $path;

会输出Car/Electrical/On-Road/Carisma