添加标签/标签&#34; <root>&#34;到XML文件</root>

时间:2014-09-22 16:59:57

标签: ruby xml nokogiri

我有一个像这样的XML文件:

<object>
 <first>23</first>
 <second>43</second>
 <third>65</third>
</object>
<object>
 <first>4</first>
 <second>3</second>
 <third>93</third>
</object>

我想在XML文件的开头添加标记/标签<root>,最后添加</root>,如下所示:

<root>
 <object>
  <first>23</first>
  <second>43</second>
  <third>65</third>
 </object>
 <object>
  <first>4</first>
  <second>3</second>
  <third>93</third>
 </object>
</root>

任何人都知道怎么做?

1 个答案:

答案 0 :(得分:0)

这比你做出来要容易得多:

require 'nokogiri'

xml = <<EOT
<object>
 <first>23</first>
 <second>43</second>
 <third>65</third>
</object>
<object>
 <first>4</first>
 <second>3</second>
 <third>93</third>
</object>
EOT

doc = Nokogiri::XML("<root>\n" + xml + '</root>')

puts doc.to_xml

# >> <?xml version="1.0"?>
# >> <root>
# >> <object>
# >>  <first>23</first>
# >>  <second>43</second>
# >>  <third>65</third>
# >> </object>
# >> <object>
# >>  <first>4</first>
# >>  <second>3</second>
# >>  <third>93</third>
# >> </object>
# >> </root>

如果您不想要XML声明:

doc = Nokogiri::XML::DocumentFragment.parse("<root>\n" + xml + '</root>')

puts doc.to_xml

# >> <root>
# >> <object>
# >>  <first>23</first>
# >>  <second>43</second>
# >>  <third>65</third>
# >> </object>
# >> <object>
# >>  <first>4</first>
# >>  <second>3</second>
# >>  <third>93</third>
# >> </object>
# >> </root>