0

I'm writing some code that opens an XML file, reads it and stores the data in a List. The only thing is that I get "XmlException data at the root level is invalid " when I run my code. I've searched on the error and non of the solutions worked for me (or I missed something).

My XML (* = censor):

<?xml version="1.0" encoding="utf-8" ?>
<Users>
<User id="1" email="***" password="***">***</User>
<User id="2" email="***" password="***">***</User>
</Users>

My C# code:

XmlDocument doc = new XmlDocument();
doc.Load("Users.xml");

XmlNode UserListNode = doc.SelectSingleNode("/Users");
XmlNodeList UserNodeList = UserListNode.SelectNodes("User");

foreach (XmlNode node in UserNodeList)
{
    Users user = new Users();
    user.id = Convert.ToInt16(node.Attributes.GetNamedItem("id").Value);
    user.name = node.InnerText;
    user.email = node.Attributes.GetNamedItem("email").Value;
    user.password = node.Attributes.GetNamedItem("password").Value;

    users.Add(user);
}

Anyone who could help?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
TDC
  • 111
  • 1
  • 1
  • 8
  • There are no quotes around the first `password` value. Did that happen when you removed the actual values or is your real XML like that? – dee-see Nov 28 '13 at 01:39
  • It happend when i removed the actual values. I just double checked and in the file it's okay. – TDC Nov 28 '13 at 01:42
  • Can you tell which method call is throwing the exception? Possibly the `UserListNode.SelectNodes("User")` call? – reuben Nov 28 '13 at 01:50
  • 2
    Is your file encoding UTF8? – Sico Nov 28 '13 at 01:52
  • I can run your code just fine. Check the encoding as suggested or if some sort of invisible character got inserted before the xml ?> line. – dee-see Nov 28 '13 at 02:06
  • I get the error on: doc.Load("Users.xml"); File is indeed encoded with UTF8. I'm now checking for invalid chars. Will keep you guys posted. – TDC Nov 28 '13 at 07:56
  • Ok, I checked it with notepad++ and textpad and no invalid chars before it :/ The file was already encoded with 'UTF8 without BOM' according to notepad++ – TDC Nov 28 '13 at 08:04
  • It's solved. I copied the XML code in notepad++ and now it worked for some reason. – TDC Nov 28 '13 at 09:03

0 Answers0