views:

91

answers:

4

Hello,

I have a quick parsing question. 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?

Bobby

A: 

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

lwe
Yep, that does not work either. Any other suggestions?
Bobby
strange - how about `doc.css('sampleDescription[comment]').first['comment']`, otherwise, which Nokogiri and Ruby version do you have installed?
lwe
A: 

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.

Jesse J
A: 

Try this:

doc.xpath("//admin/sampleDescription/@comment").to_s
KandadaBoggu
Updated the answer with the correct syntax.
KandadaBoggu
A: 

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>]

BaroqueBobcat