Search code examples
c#xml

XML Error: There are multiple root elements


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.


Solution

  • 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:

    1. Get the provider of the web service to return you actual XML that has one root node
    2. Pre-process the XML, as I've suggested above, to add a root node
    3. 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