Hello,

I'm trying to read a .xml or create the .xml if it doesn't exist or it cant find a node/child.

This is what I have so far:

bool XmlErr = false;
            if (File.Exists(XMLPath))
            {
                try
                {
                    XDocument xDoc = XDocument.Load(XMLPath);
                }
                catch
                {
                    XmlErr = true;
                }

                if (XmlErr == true)
                {
                    XmlWriterSettings xsettings = new XmlWriterSettings();
                    xsettings.Indent = true;

                    XmlWriter xwriter = XmlWriter.Create(XMLPath, xsettings);
                    xwriter.WriteStartDocument();
                    xwriter.WriteStartElement("Settings");
                    xwriter.WriteEndElement();
                    xwriter.WriteEndDocument();

                    xwriter.Flush();
                    xwriter.Close();
                }
            }
            else
            {
                XmlWriterSettings xsettings = new XmlWriterSettings();
                xsettings.Indent = true;

                XmlWriter xwriter = XmlWriter.Create(XMLPath, xsettings);
                xwriter.WriteStartDocument();
                xwriter.WriteStartElement("Settings");
                xwriter.WriteEndElement();
                xwriter.WriteEndDocument();

                xwriter.Flush();
                xwriter.Close();
            }

It works but In the Immediate Windows i get: "A first chance exception of type 'System.Xml.XmlException' occurred in System.Xml.dll" which is the "Try/Catch", Its there a better way to do this? thank you

First, expand your catch to retrieve the exception.

catch(XmlException exc)

Then, actually log/display the exception message that is contained in exc.Message. It will also give you a handy point to break on.

Unfortunately you can't tell if XML is well formed before you load it unless you write your own parser.

I'll make the program to re-create the .xml frm scratch if theres any errors on it (User modified the .xml manually), I was trying to get rid of the "A first chance exception of type 'System.Xml.XmlException' occurred in System.Xml.dll" In the immediate window, When that it cought I re-write the .xml.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.