我从Web服务获取XML。XML如下所示:
<parent> <child> Text </child> </parent> <parent> <child> <grandchild> Text </grandchild> <grandchild> Text </grandchild> </child> <child> Text </child> </parent> etc.
这是我的C#代码:
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; } } } }
我相信该错误将引发第二个父元素。如何避免此错误?任何帮助是极大的赞赏。
您需要将<parent>元素包含在周围的元素中,因为XML文档只能有一个根节点:
<parent>
<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。
因此,您有两种选择: