使用C#验证XML与XSD:根级别的数据无效。行1,位置1。

4

我正在尝试针对XSD Schema验证XML文件,但遇到了XmlException错误,消息如下:

根级别的数据无效。第1行,第1个位置。

通过查看之前类似帖子,我已经完成了以下工作:

  1. 确保文件开头没有空白字符。
  2. http://www.corefiling.com/opensource/schemaValidate.html上验证了XML和Schema。
  3. 确保我的文件编码不包含BOM。
  4. 在十六进制编辑器中双重检查BOM的缺失。XSD的前三个字符为3C 3F 78,并且XML的前三个字符也是3C 3F 78。
  5. 检查我的代码,确保使用Load()而不是LoadXml()来加载XML。

但是错误仍然存在。

我的XML加载函数如下:

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();
    }            
}

我的验证函数:

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;
    }
}

我已经将XSD和XML文件几乎全部删除,但是这个错误仍然存在。以下是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>

这里是XML:

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

有人能发现我做错了什么,或者建议进一步尝试的步骤吗?我真的很感激你们的帮助 - 我整天都在解决这个问题。

编辑问题的答案和其他可能有用的信息:

内部异常为null。堆栈跟踪是:在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)

编辑
我似乎通过在验证函数中使用StreamReader替换StringReader来解决了这个问题。

我相信StringReader只会读取XML文件的路径,而不是实际读取文件。


错误是否有内部异常? - Sayse
内部异常为空。堆栈跟踪如下:StackTrace " 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) in... 等等 - technorabble
请添加您自己的答案,我只是碰巧注意到了您的评论/编辑。 - Archlight
2个回答

2

我通过在验证函数中使用StreamReader替换StringReader来解决了这个问题。

我相信StringReader只是读取XML文件的路径,而不是实际读取文件。


0

你应该在模式中添加一个targetNamespace属性,并将其添加到XML中的根MachineParameters节点中。

<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>

我似乎通过在验证函数中将StringReader替换为StreamReader来解决了这个问题。 - technorabble

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接