Home > Enterprise >  Correct XPath for a namespaced element?
Correct XPath for a namespaced element?

Time:10-28

I was looking to get the XPath to get the value of ad:pd element. I have tried all the ways possible in the XPath to get the value, but none of then worked.

<?xml version="1.0" encoding="UTF-8"?>
<ad:sgRes
    xmlns:ad="http://www.thehtf.co.uk/Data/V1.0">
    <ad:Msg>
        <ad:cpn>
            <ad:ist>
                <ad:tm>
                    <ad:pd>12016</ad:pd>
                </ad:tm>
            </ad:ist>
        </ad:cpn>
    </ad:Msg>
</ad:sgRes>

The XPATH I used was: //pd //*:pd ad:sgRes/ad:Msg/ad:cpn/ad:ist/ad:tm/ad:pd //ad:tm/*:pd but none of them worked. Also tried using exclude-result-prefixes="ad" with no success. I have gone through few posts here but none of them worked. That's why posting my question here. Probably a very easy things for you guys to answer. But definitely I am missing something here.

CodePudding user response:

Given the posted XML, and assuming you've declared the namespace prefix similarly in your XSLT (xmlns:ad="http://www.thehtf.co.uk/Data/V1.0") this XPath,

//ad:pd

will select all pd elements in the document in the http://www.thehtf.co.uk/Data/V1.0 namespace.


One of your examples,

ad:sgRes/ad:Msg/ad:cpn/ad:ist/ad:tm/ad:pd

would have worked if the current node was the root node. Change the XPath from a relative to an absolute XPath to eliminate the dependency:

/ad:sgRes/ad:Msg/ad:cpn/ad:ist/ad:tm/ad:pd

Another of your XPaths,

//*:pd

would have worked in XPath 2.0 and up.


See also

CodePudding user response:

Have you tried this:

//*[local-name()='pd']

but preferable to use

//ad:pd

So simple.

Thanks kjhughes for your comment

  • Related