I would like to sort a Nokigiri nodeset by the title value. Tried the following code, but sorting is not working :/ Any suggestions?
doc.xpath("//item").sort{|x,y| x.xpath('foo:attr[@name="title"]/@value').text <=> y.xpath('foot:attr[@name="title"]/@value').text }
XML example:
<item>
<foo:attr name="title" value="a"/>
</item>
<item>
<foot:attr name="title" value="c"/>
</item>
<item>
<foor:attr name="title" value="b"/>
</item>
Output I am looking for: (nodeset)
<item>
<foo:attr name="title" value="a"/>
</item>
<item>
<foot:attr name="title" value="b"/>
</item>
<item>
<foor:attr name="title" value="c"/>
</item>
If I understand your request, you want to remove them, then sort the array, then add them back:
xml = Nokogiri::XML.parse(data)
nodes = xml.root.css("item").remove
nodes.sort_by{ |node|
node.css("attr")[0].attr("value"))
}.each{ |node|
xml.root.add_child(node)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.