Reputation: 765
I am using XPath in unix to get the value of attribute as follows:
xpath PM.xml '/*[contains(local-name(),'PM')]/*[contains(local-name(),'family')]/@eventNumber'
which is returning me:
Found 4 nodes:
-- NODE --
eventNumber="000000"-- NODE --
eventNumber="010000"-- NODE --
eventNumber="020000"-- NODE --
eventNumber="030000"
But here I need the value as:
000000
010000
020000
030000
After looking into some examples, I tried functions like string()
, text()
as follows, but didn't work.
SS-03:~/pankaj # xpath PM.xml '/*[contains(local-name(),'PM')]/*[contains(local-name(),'family')]/@eventNumber/text()'
No nodes found
SS-03:~/pankaj # xpath PM.xml '/*[contains(local-name(),'PM')]/*[contains(local-name(),'family')]/@eventNumber/string()'
Parse of expression /*[contains(local-name(),PM)]/*[contains(local-name(),family)]/@eventNumber/string() failed - junk after end of expression: ( at /usr/lib/perl5/vendor_perl/5.10.0/XML/XPath/Parser.pm line 127.
Please correct me where I am wrong. Also, please help me to get this using xpath only, as I have to use this in XSL.
Upvotes: 0
Views: 1661
Reputation: 89325
Your xpath is fine, that's only the way the application you used display xpath result. For example, the same xpath when used in XSL like so :
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- set output method to be plain text -->
<xsl:output method="text"/>
<xsl:template match="/">
<!-- using exactly the same xpath -->
<xsl:apply-templates select="/*[contains(local-name(),'PM')]/*[contains(local-name(),'family')]/@eventNumber"/>
</xsl:template>
<xsl:template match="@*">
<!-- print attribute value -->
<xsl:value-of select="."/>
<!-- print newline character -->
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
given the following input XML :
<?xml version="1.0" encoding="utf-8"?>
<PM xmlns="foo">
<family eventNumber="000000"/>
<family eventNumber="010000"/>
<family eventNumber="020000"/>
<family eventNumber="030000"/>
</PM>
yield the expected values in output :
000000
010000
020000
030000
Upvotes: 1
Reputation: 26153
With xpath 2.0 you can get the value of attribute with function string() at the end of your expression
... /@eventNumber/string()
but never in xpath 1. Only by post processing or, if you waiting one result,
string( ... /@eventNumber )
Upvotes: 1