2014-09-22 207 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>