将标签/标记"<root>"添加到 XML 文件



我有一个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>

有人知道怎么做吗?

这比你想象的要容易得多:

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>

相关内容

  • 没有找到相关文章

最新更新