XML 错误:有多个根元素 [英] XML Error: There are multiple root elements
问题描述
我从 Web 服务获取 XML.这是 XML 的样子:
I am getting XML from a web service. Here is what the XML looks like:
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
etc.
这是我的 C# 代码:
And here is my C# code:
StringBuilder output = new StringBuilder();
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xoResponse.@return)))
{
XmlWriterSettings ws = new XmlWriterSettings();
//ws.Indent = true;
using (XmlWriter writer = XmlWriter.Create(output, ws))
{
// Parse the file and display each of the nodes.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(reader.Name);
break;
case XmlNodeType.Text:
writer.WriteString(reader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
break;
}
}
}
}
我相信错误是在第二个父元素上引发的.我怎样才能避免这个错误?非常感谢任何帮助.
I believe that the error is thrown on the second parent element. How can I avoid this error? Any help is greatly appreciated.
推荐答案
您需要将
元素括在周围元素中,因为 XML 文档只能有一个根节点:>
You need to enclose your <parent>
elements in a surrounding element as XML Documents can have only one root node:
<parents> <!-- I've added this tag -->
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
</parents> <!-- I've added this tag -->
由于您是从其他地方接收此标记,而不是自己生成它,因此在尝试将其解析为 XML 之前,您可能必须通过将响应视为字符串并用适当的标签包装它来自己执行此操作.
As you're receiving this markup from somewhere else, rather than generating it yourself, you may have to do this yourself by treating the response as a string and wrapping it with appropriate tags, prior to attempting to parse it as XML.
所以,您有几个选择:
- 让网络服务的提供者返回给你实际具有一个根节点的 XML
- 按照我上面的建议对 XML 进行预处理,以添加根节点
- 预处理 XML 以将其拆分为多个块(即每个
节点一个)并将每个块作为一个不同的 XML 文档进行处理
- Get the provider of the web service to return you actual XML that has one root node
- Pre-process the XML, as I've suggested above, to add a root node
- Pre-process the XML to split it into multiple chunks (i.e. one for each
<parent>
node) and process each as a distinct XML Document
这篇关于XML 错误:有多个根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!