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.
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 <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 -->
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:
<parent>
node) and process each as a distinct XML Document