简体   繁体   中英

XDocument Exception: Root element is missing

I have a simple XML file:

<?xml version="1.0" encoding="utf-8" ?>
<Config>
<NumOfBytesInRow>20</NumOfBytesInRow>
<FirstBaudRate>115200</FirstBaudRate>
<SecondBaudRate>34800</SecondBaudRate>
<DefaultPort>COM1</DefaultPort>
<NumOfTries>2</NumOfTries>
</Config>

And I'm trying to get the elements, but as soon as I'm opening the file I'm getting an exception that the root element is missing

XDocument doc = new XmlDocument();
        doc.Load(path);

EDIT

I have added:

if(File.Exists("D:\\BBConfig.xml"))

before the load it found the file and still same error

For the first I find the answer of user3890766 very good: "This exception could be thrown if the method can't find the file". But nevertheless you can try this for sure:

    string strXml;
    try
    {
        using (StreamReader sr = new StreamReader("myXML.xml"))
        {
             strXml = sr.ReadToEnd();
        }

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(strXml);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }

This exception could be thrown if the method can't find the file. You need to check if your application can find the file at the given path, and have the authorization to read it.

To be sure, you could use a Stream , and check the Length . Then use XmlDocument.Load with this Stream .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM