how to select attribute value of a node in XQuery?
Asked Answered
Q

2

33

In below XML:

<company>
    <customers>
    <customer cno="2222">
            <cname>Charles</cname>
            <street>123 Main St.</street>
            <city>Wichita</city>
            <zip>67226</zip>
            <phone>316-636-5555</phone>
        </customer>
        <customer cno="1000">
            <cname>Bismita</cname>
            <street>Ashford Dunwoody</street>
            <city>Wichita</city>
            <zip>67226-1555</zip>
            <phone>000-000-0000</phone>
        </customer>     
    </customers>
</company>

I need to get the customer's no which is an attribute. In XPath I know it is /company/customers/customer/@cno, in XQuery I've tried below expression but didn't work for me:

for $c in /company/customers/customer
return $c/@cno
Quickel answered 17/4, 2013 at 1:40 Comment(5)
XQuery uses plain XPath; your attempt works for me. What does return $c give you?Leprous
I'm using EditX software for this, but it show error "Cannot create an attribute node whose parent is document node." Can you please let me know in which tool you try this, so I can switch to that tool. May be it is tool specific issue.Quickel
possible duplicate of Using XQuery/XPath to get the attribute value of an element's parent nodeLeprous
Sometimes searching for the exact error message does wonders. It turned up this question as the first hit for me, I'm sure it would have done the same for you.Leprous
You can also use the shorter /company/customers/customer/@cno/data() which doesn't require an explicit loop.Camelopardus
C
57

You should use data to pick attribute value:-

for $c in /company/customers/customer
return data($c/@cno)
Copyright answered 17/4, 2013 at 5:11 Comment(0)
A
16

You can also use string to get attribute value:

for $c in /company/customers/customer
    return $c/@cno/string()
Alon answered 4/3, 2015 at 13:17 Comment(1)
I was able to get this to work where wrapping it in data() did not. I think its because my parser is strictly older xpath/xquery.Certes

© 2022 - 2024 — McMap. All rights reserved.