我知道如何使用Nokogiri解析XML文档。我有一个元素,我想重新排序文本字符串,所以我想要就地编辑或只是写一个全新的文件。有人可以帮忙吗?
答案 0 :(得分:0)
以下是一个示例,当然,您必须修改它以使用XML。
鉴于您的XML类似于:
<top>
<node1>
<value>mmm</value>
<value>zzz</value>
<value>ccc</value>
</node1>
<anothernode>
<value>zzz</value>
<value>ccc</value>
</anothernode>
</top>
如果你想让node1的子节点按字母顺序排列,你可以这样做:
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}
然后n.to_s应该等于:
<top>
<node1>
<value>ccc</value>
<value>mmm</value>
<value>zzz</value>
</node1>
<anothernode>
<value>zzz</value>
<value>ccc</value>
</anothernode>
</top>
可能有更有效的方法来实现这一点,特别是我正在寻找一种记录的方法来同时取消所有孩子的链接(可能是node1.children = []?)或Nokogiri方式来对节点进行排序。有关其他方法,请查看Nokogiri docs。