tags:

views:

155

answers:

2

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(void):string and I am not willing to write one by my own. is there any known lite 3rd party Solution ??

+1  A: 

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_')]
Tomasz Struczyński
+2  A: 

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.

Josh Davis
I could do this using ID.rather my current version is done using ID.Rather I was in search of Something else. I've made a different thread for that http://stackoverflow.com/questions/2644163/php-domxml-xpath-of-recursive-xpointer