开发者

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 wo开发者_JAVA百科rk. What am I missing?


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


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.


Try this:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜