在Php / SimpleXml中获取xml节点的完整路径

时间:2018-01-31 08:00:05

标签: php xml xpath simplexml

我需要xml节点的完整路径 我在this question看到了答案,但我无法使用它。

我在php web测试器上使用的代码下面没有成功:

$xml = <<<EOF
<root>
    <First>
        <Martha>Text01</Martha>
        <Lucy>Text02</Lucy>
        <Bob>
            <Jhon>Text03</Jhon>
        </Bob>
        <Frank>One</Frank>
        <Jessy>Two</Jessy>
    </First>
    <Second>
        <Mary>
            <Jhon>Text04</Jhon>
            <Frank>Text05</Frank>
            <Jessy>Text06</Jessy>
        </Mary>
    </Second>
</root>
EOF;

$MyXml = new SimpleXMLElement($xml);
$Jhons = $MyXml->xpath('//Jhon');
foreach ($Jhons as $Jhon){
    echo (string) $Jhon;
    //No one of the following works
    echo (string) $Jhon->xpath('./node()/path()');
    echo (string) $Jhon->xpath('./path()');
    echo (string) $Jhon->xpath('.path()');
    echo (string) $Jhon->path();
    echo '<br/> ';
}

我需要:&#34; / root / First / Bob / Jhon&#34;和&#34; / root / Second / Mary / Jhon&#34;

1 个答案:

答案 0 :(得分:2)

你可以使用更强大的DOM(基于PHP的DOMDocument)api来做到这一点......

$MyXml = new SimpleXMLElement($xml);
$Jhons = $MyXml->xpath('//Jhon');
foreach ($Jhons as $Jhon){
    $dom = dom_import_simplexml($Jhon);
    echo $dom->getNodePath().PHP_EOL;
}

dom_import_simplexml($Jhon)转换节点,然后getNodePath()显示路径...

这给出了(例如)

/root/First/Bob/Jhon
/root/Second/Mary/Jhon

或者如果您只想坚持使用SimpleXML,您可以使用XPath轴祖先或自我列出当前节点和每个父节点......

$MyXml = new SimpleXMLElement($xml);
$Jhons = $MyXml->xpath('//Jhon');
foreach ($Jhons as $Jhon){
    $parent = $Jhon->xpath("ancestor-or-self::*");
    foreach ( $parent as $p )   {
        echo "/".$p->getName();
    }
    echo PHP_EOL;
}