简体   繁体   English

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

[英]Get xml node full path in Php / SimpleXml

I need the full path of an xml node. 我需要xml节点的完整路径。
I saw the answer in this question but I wasn't able to use it. 我看到了这个问题的答案,但无法使用。

Below the code I used on a php web tester with no success: 下面我在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/> ';
}

I need: "/root/First/Bob/Jhon" and "/root/Second/Mary/Jhon" 我需要:“ / root / First / Bob / Jhon”和“ / root / Second / Mary / Jhon”

You can use the much more powerful DOM (DOMDocument based in PHP) api to do this... 您可以使用功能更强大的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;
}

The dom_import_simplexml($Jhon) converts the node and then getNodePath() displays the path... dom_import_simplexml($Jhon)转换节点,然后getNodePath()显示路径...

This gives ( for the example) 这给出了(例如)

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

Or if you just want to stick to SimpleXML, you can use the XPath axes ancestor-or-self to list the current node and each parent node... 或者,如果您只想坚持使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM