2014-09-22 209 views
0

我有这样一个XML文件:标签/标签“<root>”添加到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> 

任何人都知道如何做到这一点?

+0

你的第一个“XML fragement”是无效的XML。您无法将其加载到XML解析器中。什么是制作你的第一个片段?也许你可以改变生产方式。有效的XML有一个根标签,就像在第二个XML片段中一样。 – Sjips 2014-09-22 17:24:20

+0

xml在没有标签的情况下找到我。 如何添加标签 Javi 2014-09-23 00:37:07

回答

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>