How to find text in XML and display its sibling with Nokogiri?

I have the following XML used in the REST API:

<dataitems> <dataitem colour="null"> <value> <label>Intel</label> <count>43</count> </value> <value> <label>AMD</label> <count>39</count> </value> <value> <label>ARM</label> <count>28</count> </value> </dataitem> </dataitems> 

I would like to search for text in the <label> and display the match value for <count> in the table.

In the controller, I have: @post_count = Nokogiri::XML(Post.item_data.to_xml) .

In the view, I'm not sure if I need to use @post_count.xpath or @post_count.search .

Can someone point me in the right direction with the correct method and syntax for it?

Thanks in advance.

+4
source share
1 answer

Although I'm not sure what information you are looking for, I have a few suggestions.

1) If you know the value in the element before performing a search:

 doc = Nokogiri.XML(open(source_xml)) # Assuming there is only one of each label node = doc.xpath('//label[text()="Intel"]').first count = node.next_element.text # or if there are many of each label nodes = doc.xpath('//label[text()="Intel"]') nodes.each {|node| count = node.next_element.text # do something with count here } 

2) Assuming you donโ€™t know the names in the tag in advance

 doc = Nokogiri.XML(open(source_xml)) labels = {} doc.xpath('//label').each {|node| labels[node.text] = node.next_element.text } # labels => {"Intel"=>"43", "AMD"=>"39", "ARM"=>"28"} 

I personally like the second solution better because it gives you a clean hash, but I prefer to work with hashes and arrays as quickly as possible.

+4
source

Source: https://habr.com/ru/post/1400777/


All Articles