I know how to parse through an XML document with No开发者_StackOverflowkogiri. I have one element in which I want to re-sort the text strings, so I was thinking of either editing in-place or just writing a whole new file. Can anyone help?
Here's an example, you'll have to modify this to work with your XML, of course.
Given your XML is something like:
<top>
<node1>
<value>mmm</value>
<value>zzz</value>
<value>ccc</value>
</node1>
<anothernode>
<value>zzz</value>
<value>ccc</value>
</anothernode>
</top>
And if you wanted to make the children of node1 be in alphabetical order by value, you could do:
n = Nokogiri::XML(the_xml_i_wrote_above)
node1 = n.xpath("//node1").first
sorted_children = node1.children.sort{|x,y| x.text <=> y.text }
node1.children.each {|x| x.unlink }
sorted_children.each {|x| node1 << x}
And then n.to_s should be equal to:
<top>
<node1>
<value>ccc</value>
<value>mmm</value>
<value>zzz</value>
</node1>
<anothernode>
<value>zzz</value>
<value>ccc</value>
</anothernode>
</top>
There might be more efficient ways to do this, in particular I was looking for a documented way to unlink all children at once (maybe node1.children = [] ?) or a Nokogiri way to sort the nodes. Take a look at the Nokogiri docs for other ways to do this.
精彩评论