Search code examples
c#xml

Strange behavior when loading xml via XmlDocument


I am receiving an error regarding improper format when loading an xml document in c#. When using the following code,

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(fileName);

I receive the error afterwards:

Data at the root level is invalid. Line 1, position 1.

However, if I change the first occurrence to the following, everything works as expected and the type of xmlDoc is in fact XmlDocument:

var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(fileName);

A snippet of my xml is file is below:

<?xml version="1.0" encoding="utf-8"?>
<AutomatedTests type="asdf">
    <TestGroup>
    </TestGroup>
</AutomatedTests>

Is there any explanation as to why this could be happening?


Solution

  • Assuming filename is the path, try the below code.

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(fileName);
    

    XmlDocument.Load loads XML either from a stream, TextReader, path/URL, or XmlReader and XmlDocument.LoadXml loads the XML contained within a string.