开发者

PHP Getting XPath of a DOMNode

I am creating an XML document on the fly. and I need to know the XPath of the Node I've just created. I don't see any such function like DOMNode::calculateXPath(vo开发者_StackOverflowid):string and I am not willing to write one by my own. is there any known lite 3rd party Solution ??


There was a similar question a while ago, for which I posted something along those lines:

function calculateXPath(DOMNode $node)
{
    $q     = new DOMXPath($node->ownerDocument);
    $xpath = '';

    do
    {
        $position = 1 + $q->query('preceding-sibling::*[name()="' . $node->nodeName . '"]', $node)->length;
        $xpath    = '/' . $node->nodeName . '[' . $position . ']' . $xpath;
        $node     = $node->parentNode;
    }
    while (!$node instanceof DOMDocument);

    return $xpath;
}

As mentioned by Tomasz though, it is definitely not as robust or future-proof as using id's.


There's no definite XPath for given node, because XPath is a a search query. Like in google, you can find specific page using different search terms. What's more, XPath query returning current node can (probably will) change when you modify DOM tree, so the path you can get is valid only until next tree modification is done.

You may give each of your nodes unique ID or class name (class is safer when you want to use other IDs - there can be multiple classes and only one ID). Then you can search using this class/id.

Example for tag span and class unique_1_:

//span[contains(@class, 'unique_1_')]


I know this is a bit old, but I am adding this just in case someone else is looking for this.

As of PHP 5.2 there is DomNode::getNodePath() in which DomElement extends.

See: http://www.php.net/manual/en/domnode.getnodepath.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜