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
howlger
  • 31,050
  • 11
  • 59
  • 99
Itz.Irshad
  • 1,014
  • 5
  • 23
  • 44
  • XQuery uses plain XPath; your attempt works for me. What does `return $c` give you? – Tomalak Apr 17 '13 at 02:39
  • 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. – Itz.Irshad Apr 17 '13 at 02:49
  • possible duplicate of [Using XQuery/XPath to get the attribute value of an element's parent node](http://stackoverflow.com/questions/2166014/using-xquery-xpath-to-get-the-attribute-value-of-an-elements-parent-node) – Tomalak Apr 17 '13 at 07:01
  • 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. – Tomalak Apr 17 '13 at 07:03
  • You can also use the shorter `/company/customers/customer/@cno/data()` which doesn't require an explicit loop. – Jens Erat Apr 17 '13 at 07:35

2 Answers2

57

You should use data to pick attribute value:-

for $c in /company/customers/customer
return data($c/@cno)
Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
Navin Rawat
  • 3,208
  • 1
  • 19
  • 31
16

You can also use string to get attribute value:

for $c in /company/customers/customer
    return $c/@cno/string()
fedorqui
  • 275,237
  • 103
  • 548
  • 598
Nikunj Vekariya
  • 833
  • 5
  • 19
  • 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. – Jeff Meden Jan 06 '16 at 21:19