简体   繁体   English

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

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

I am trying to validate an XML file against a XSD Schema, and am encountering an XmlException, message 我正在尝试针对XSD架构验证XML文件,并且遇到XmlException消息

Data at the root level is invalid. 根级别的数据无效。 Line 1, position 1. 第1行,位置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 http://www.corefiling.com/opensource/schemaValidate.html上验证了XML和架构
  3. Ensured my files are encoded without BOM. 确保我的文件编码没有 BOM。
  4. Double-checked the absence of BOM in a hex editor. 在十六进制编辑器中再次检查了BOM表的缺失。 First three characters of the XSD are 3C 3F 78, and the first three characters of the XML are also 3C 3F 78. XSD的前三个字符是3C 3F 78,而XML的前三个字符也是3C 3F 78。
  5. Checked my code to ensure I was loading the XML using Load() and not LoadXml() 检查我的代码以确保我使用Load()而不是LoadXml()加载XML

But the error persists. 但是错误仍然存​​在。

My XML loading function reads: 我的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();
    }            
}

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. 我已经将XSD和XML文件完全删除了,但是这个错误仍然存​​在。 Here is the XSD: 这是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:

<?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. 我真的很感谢您的帮助-我整天都在ash头。

EDIT Answers to questions, and other potentially useful info: 编辑问题的答案,以及其他可能有用的信息:

Inner exception is null. 内部异常为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) 堆栈跟踪为:在System.Xml.XmlTextReaderImpl.Throw(Exception e)\\ r \\ n在System.Xml.XmlTextReaderImpl.Throw(String res,String arg)\\ r \\ n在System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()\\在System.Xml.XmlTextReaderImpl.Read()处System.Xml.Xml.XsdValidatingReader.Read()处的r \\ n在System.Xml.XmlTextReaderImpl.ParseDocumentContent()\\ r \\ n在Configuration.PLCConfigurationTool处。 PlcConfigurationData.ValidateXml(字符串xmlPath,字符串schemaPath)

Edit 编辑
I appear to have fixed this issue by replacing StringReader with StreamReader in the validation function. 我似乎通过在验证功能中将StreamReader替换为StringReader来解决此问题。

StringReader would have just been reading the path of the XML file, rather than actually reading the file, I believe. 我相信,StringReader只会读取XML文件的路径,而不是实际读取文件。

I appear to have fixed this issue by replacing StringReader with StreamReader in the validation function. 我似乎通过在验证功能中将StreamReader替换为StringReader来解决此问题。

StringReader would have just been reading the path of the XML file, rather than actually reading the file, I believe. 我相信,StringReader只会读取XML文件的路径,而不是实际读取文件。

You should add a targetNamespace attribute to the schema, and add it to the root MachineParameters node in the xml as well. 您应该将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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# XML 解析 - 根级别的数据无效。 第 1 行,位置 1 - C# XML Parsing - Data at the root level is invalid. Line 1, position 1 来自 URL 的 C# XML - 根级别的数据无效。 第 1 行,位置 1 - C# XML from URL - Data at the root level is invalid. Line 1, position 1 根级别的数据无效。 第1行,内存xml中有效的位置1 - Data at the root level is invalid. Line 1, position 1 on valid in memory xml “根级别的数据无效。第 1 行,position 1”解析 XML 时 - "Data at the root level is invalid. Line 1, position 1" When Parsing XML 根级别的数据无效。 第1行在XML中的位置1 - data at the root level is invalid. line 1 position 1 in XML xml.LoadData - 根级别的数据无效。 1号线,position 1 - xml.LoadData - Data at the root level is invalid. Line 1, position 1 根级别的数据无效。 第1行,位置1 - Data at the root level is invalid. Line 1, position 1 C#XmlDocument.LoadXml(string)失败-根级别的数据无效。 第1行的位置1。 - C# XmlDocument.LoadXml(string) fail -data at the root level is invalid. line 1 position 1. xmldocument URL 中的 XML - 根级别的数据无效。 第 1 行,位置 1 为什么它适用于一个 URL 而不是另一个? - XML from URL - Data at the root level is invalid. Line 1, position 1 Why it works with one URL and not the other? SolrNET-根级别的数据无效。 第1行,位置1 - SolrNET - Data at the root level is invalid. Line 1, position 1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM