I am getting XML from a web service. Here is what the XML looks like:
Text
Text
Text
Text
etc.
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.
解决方案
You need to enclose your elements in a surrounding element as XML Documents can have only one root node:
Text
Text
Text
Text
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.
So, you've a couple of choices:
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 node) and process each as a distinct XML Document