使用Nokogiri读取XML文件是否需要根元素?

nil*_*jan 2 ruby xml nokogiri

当它不包含"root"时,我在读取XML文件时遇到问题.

如果我有这样的文件:

<?xml version="1.0" encoding="utf-8"?>
<a>
<country>US</country>
</a>
<b>
<country>UK</country>
</b>
Run Code Online (Sandbox Code Playgroud)

Nokogiri似乎只阅读第一个元素.如果XML文件有根元素,它似乎工作正常.我正在使用Nokogiri 1.5.6.

这有效:

<?xml version="1.0" encoding="utf-8"?>
<root>
<a>
<country>US</country>
</a>
<b>
<country>UK</country>
</b>
</root>
Run Code Online (Sandbox Code Playgroud)

Mar*_*mas 5

没有根元素,它不是一个完整的XML文档.您可以在解析之前将XML包装在根元素中,也可以Nokogiri::XML::DocumentFragment从中创建一个.

理想情况下,您可以修复创建XML的任何内容.