Validating XML against XSD using C#: Data at the root level is invalid. Line 1, position 1

StackOverflow https://stackoverflow.com/questions/18130182

  •  24-06-2022
  •  | 
  •  

Question

I am trying to validate an XML file against a XSD Schema, and am encountering an XmlException, message

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

Based on a crawl through previous similar posts I have done the following:

  1. Ensured that there is no whitespace at the start of the files.
  2. Validated the XML and Schema at http://www.corefiling.com/opensource/schemaValidate.html
  3. Ensured my files are encoded without BOM.
  4. Double-checked the absence of BOM in a hex editor. First three characters of the XSD are 3C 3F 78, and the first three characters of the XML are also 3C 3F 78.
  5. Checked my code to ensure I was loading the XML using Load() and not LoadXml()

But the error persists.

My XML loading function reads:

public void LoadXml(ref XmlDocument target, string path)
{
    try
    {                
        target = new XmlDocument();                
        target.Load(path);
    }
    catch (XmlException ex)            
    {
        // Exception is thrown is there is an error in the Xml
        MessageBox.Show(string.Format("An XML Exception was thrown while loading the XML file from {0}.\nException text: {1}\nXML file line: {2}", path, ex.Message, ex.LineNumber));
        Application.Exit();
    }
    catch (Exception ex)             
    {
        // General exception
        MessageBox.Show(string.Format("A General Exception was thrown while loading the XML file from {0}.\nException text: {1}", path, ex.Message));
        Application.Exit();
    }            
}

And my validation function:

private bool ValidateXml(string xmlPath, string schemaPath)
{
    try
    {
        XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
        xmlReaderSettings.ValidationEventHandler += XmlReaderValidationEventHandler;

        xmlReaderSettings.CloseInput = true;
        xmlReaderSettings.ValidationType = ValidationType.Schema;
        xmlReaderSettings.Schemas.Add(null, Settings.Default.SchemaPath);
        xmlReaderSettings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings |
                                                XmlSchemaValidationFlags.ProcessIdentityConstraints |
                                                XmlSchemaValidationFlags.ProcessInlineSchema |
                                                XmlSchemaValidationFlags.ProcessSchemaLocation;
        StringReader sr = new StringReader(Settings.Default.PlcXmlPath);
        using (XmlReader validatingReader = XmlReader.Create(sr, xmlReaderSettings))
        {                    
            while (validatingReader.Read())
            {
                // Loop through the document
            }
        }

        return true;
    }
    catch (XmlSchemaValidationException ex)
    {
        MessageBox.Show(string.Format("Unable to validate XML file {0} against schema {1}\nException text: {2}\nXML Line: {3}\nData: {4}", xmlPath, schemaPath, ex.Message, ex.LineNumber, ex.Data));
        return false;
    }
    catch (Exception ex)
    {
        MessageBox.Show(string.Format("Unable to validate XML file {0} against schema {1}\nException text: {2}", xmlPath, schemaPath, ex.Message));
        return false;
    }
}

I have taken my XSD and XML files all the way down to pretty much nothing, but this error remains. Here is the XSD:

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="MachineParameters">

    </xsd:element>
</xsd:schema>

And here is the XML:

<?xml version="1.0" encoding="utf-8"?>
<MachineParameters>Test
</MachineParameters>

Can anyone spot what I've done wrong, or suggest any further steps to try? I would really appreciate your help - I have been bashing my head against this all day.

EDIT Answers to questions, and other potentially useful info:

Inner exception is null. Stack trace is: at System.Xml.XmlTextReaderImpl.Throw(Exception e)\r\n at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)\r\n at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()\r\n at System.Xml.XmlTextReaderImpl.ParseDocumentContent()\r\n at System.Xml.XmlTextReaderImpl.Read()\r\n at System.Xml.XsdValidatingReader.Read()\r\n at Configuration.PLCConfigurationTool.PlcConfigurationData.ValidateXml(String xmlPath, String schemaPath)

Edit
I appear to have fixed this issue by replacing StringReader with StreamReader in the validation function.

StringReader would have just been reading the path of the XML file, rather than actually reading the file, I believe.

Was it helpful?

Solution

I appear to have fixed this issue by replacing StringReader with StreamReader in the validation function.

StringReader would have just been reading the path of the XML file, rather than actually reading the file, I believe.

OTHER TIPS

You should add a targetNamespace attribute to the schema, and add it to the root MachineParameters node in the xml as well.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://myschema">
.
.
.

<?xml version="1.0" encoding="utf-8"?>
<MachineParameters xmlns="myschema">Test
</MachineParameters>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top