Yadong
Yadong

Reputation: 441

Cannot query using XPath when data element has attribute **xmlns="..."**

I have difficulty to query the value of a data element value, when attribute xmlns="..." in it and it's parents element. The following example is part of a SOAP response, and I want to get the value of first name and last name of it by using XPATH /PartyInq_v2Response/PartyInq_v2Rs_Type/*[local-name()="person"]/firstName' . But it return nothing. It can return value if I removed all xmlns="..." from the xml before query. Does anybody know how to query first name from the example directly?

<PartyInq_v2Response xmlns="urn:Somewhere.Int" xmlns:q2="http://SomewhereOps.v20120719" xmlns:q10="http://SomewhereTypes.v20120719.GenericTypes">
    <PartyInq_v2Rs_Type>
        <q2:person>
            <firstName xmlns="http://SomewhereTypes.v20120719.Types">somebody</firstName>
            <lastName xmlns="http://SomewhereTypes.v20120719.Types">nobody</lastName>           
        </q2:person>
    </PartyInq_v2Rs_Type>
</PartyInq_v2Response>

Thanks

Lu

Upvotes: 1

Views: 383

Answers (1)

hr_117
hr_117

Reputation: 9627

It is not clear what xslt processor you are using. But you have to make all used namespaces known to xlst.

The following xlst will do:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:s="urn:Somewhere.Int" 
            xmlns:q2="http://SomewhereOps.v20120719"
            xmlns:q10="http://SomewhereTypes.v20120719.GenericTypes"
            xmlns:t="http://SomewhereTypes.v20120719.Types">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/" >
        <xsl:value-of select="/s:PartyInq_v2Response/s:PartyInq_v2Rs_Type/q2:person/t:firstName"/>
    </xsl:template>
</xsl:stylesheet>

If the namespace url is not known you can use local-name().

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
             xmlns:s="urn:Somewhere.Int" >
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/" >
        <xsl:value-of select="/s:PartyInq_v2Response/*[local-name() = 'PartyInq_v2Rs_Type']/*[local-name() = 'person']/*[local-name()='firstName']"/>
    </xsl:template>
</xsl:stylesheet>

Upvotes: 1

Related Questions