1

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.

1
  • its the whole xml where values "newbgm" and "123456789" will get changed dynamically Commented Mar 17, 2016 at 15:27

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Keith. But when i execute it throws me "'v' is an unexpected token. Expecting white space. Line 4, position 17." The idea is to search for "migr" in the xml string, after finding "::" needs to be ommited. Then it will find "tft1"and so on
it works for me with the xml you provided in the question. Can you double check the contents of the xml file you are parsing?
why do you have a double quote followed by a singe quote?
Thanks Keith. My bad. i missed a "_" in the tag. But doesn't it display the values like "migr" , tft1, 123456789, etc in the console.,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.