newbie1
newbie1

Reputation: 13

Query on XML parsing in C#?

But it gives me exception like "There are multiple root elements. Line 3, position 2." on the line reader.MoveToContent();

Below is the sample code that i use

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace sample
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("C:\\Users\\ADMIN\\Pictures\\test.xml");
            string contents = "";
            while (reader.Read())
            {
                reader.MoveToContent();
                if (reader.NodeType == System.Xml.XmlNodeType.Element)
                    contents += "<" + reader.Name + ">\n";
                if (reader.NodeType == System.Xml.XmlNodeType.Text)
                    contents += reader.Value + "\n";
            }
            Console.Write(contents);
            Console.ReadLine();
        }

    }
}

please help.

Upvotes: 1

Views: 66

Answers (1)

Keith Hall
Keith Hall

Reputation: 16055

You are trying to parse an XML document, that, stand-alone, isn't valid XML. Therefore, you need to tell it that it is only a fragment. This will prevent it from throwing an error about multiple root elements.

You can do this by replacing the line

System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("C:\\Users\\ADMIN\\Pictures\\test.xml");

with:

var settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
var reader = System.Xml.XmlTextReader.Create("C:\\Users\\ADMIN\\Pictures\\test.xml", settings);

Upvotes: 2

Related Questions