开发者

Can I use ruby to edit an XML file in place, like with Nokogiri?

开发者 https://www.devze.com 2023-01-31 11:38 出处:网络
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 writ

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.

0

精彩评论

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