0

I'm trying to load ";" in a Xml document to my form at the code worked fine until yesterday when I got the error message below for some reson, I haden't made any changes to the code.

Error: "An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll Additional information: Data at the root level is invalid. Line 1, position 1."

The Code:

XmlDocument myContacts = new XmlDocument();
string path = "C:\\Users\\Name\\\mycontacts.xml";

private void LoadContacts()
    {
        myContacts.LoadXml(path);

        foreach (XmlNode node in myContacts.SelectNodes("Contacts/Contact"))
        {
            lstContacts.Items.Add(node.SelectSingleNode("Name").InnerText);
        }
    }

I've tried Linq (XDocument) to but get the same problem there but at ";" in the Program.cs Main.

Application.Run(new Form1());

I've googled around and tried James Schubert's solution with no result.

XML:

 <?xml version="1.0" encoding="UTF-8"?>
 <Contacts>
    <Contact>
        <Name>Testing</Name>
        <Email>test@gmail.com</Email>
        <Phone>070 00 00 000</Phone>
        <Street>Test A1</Street>
        <Zip>000 00</Zip>
        <Town>Testing</Town>
    </Contact>
</Contacts>

I know there's lots of threads on the topic already but can't get any of their answers/solutions to work.

Is there any more "magic" ways to deal with this problem than the ones I've been able to find when searching for solutions?

Perly X
  • 45
  • 1
  • 7
  • 1
    More detailed difference between Load/LoadXml - http://stackoverflow.com/questions/1660676/xmldocument-load-vs-xmldocument-loadxml. – Alexei Levenkov Sep 06 '16 at 07:45

1 Answers1

2

XmlDocument.LoadXml is for parsing an XML string. An example from the docs:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");

To load from a file, use XmlDocument.Load.

As an aside, I'd suggest you look at LINQ to XML if you haven't already. It's a much nicer API.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45
  • 1
    Not exactly novel approach, but indeed correct (plenty of similar posts like http://stackoverflow.com/questions/1660676/xmldocument-load-vs-xmldocument-loadxml) – Alexei Levenkov Sep 06 '16 at 07:44