Bobby
Bobby

Reputation: 271

Select attribute from node with XPath

I have a file with the following structure

<admin>
 <sampleName>Willow oak leaf</sampleName>
 <sampleDescription comment="Total genes">
  <cvParam cvLabel="Bob" accession="123" name="Oak" />      
 </sampleDescription> 
</admin>

I'm trying to get out the text "Total genes" after the sampleDescription comment, and I have used the following code:

sampleDescription = doc.xpath( "/admin/Description/@comment" )
sampleDescription = doc.xpath( "/admin/Description" ).text

But neither work. What am I missing?

Upvotes: 2

Views: 1659

Answers (4)

Harish Shetty
Harish Shetty

Reputation: 64363

Try this:

doc.xpath("//admin/sampleDescription/@comment").to_s

Upvotes: 1

BaroqueBobcat
BaroqueBobcat

Reputation: 10150

doc.xpath returns a NodeSet which acts a bit like an array. So you need to grab the first element

doc.xpath("//admin/sampleDescription").first['comment']

You could also use at_xpath which is equivalent to xpath(foo).first

doc.at_xpath("//admin/sampleDescription")['comment']

Another thing to note is that attributes on nodes are accessed like hash elements--with [<key>]

Upvotes: 0

Jesse Jashinsky
Jesse Jashinsky

Reputation: 10663

It's not working because there's no Description element. As mentioned by Iwe, you need to do something like sampleDescription = doc.xpath("/admin/sampleDescription/@comment").to_s

Also, if it were me, I would just do sampleDescription = doc.xpath("//sampleDescription/@comment").to_s. It's a simpler xpath, but it might be slower.

And as a note, something that trips up a lot of people are namespaces. If your xml document uses namespaces, do sampleDescription = doc.xpath("/xmlns:admin/sampleDescription/@comment").to_s. If your doc uses namespaces and you don't specify it with xmlns:, then Nokogiri won't return anything.

Upvotes: 1

lwe
lwe

Reputation: 2625

might be a typo... have you tried doc.xpath("/admin/sampleDescription/@comment").text?

Upvotes: 1

Related Questions