开始使用 .NET 进行 XSD 验证

时间:2023-03-30
本文介绍了开始使用 .NET 进行 XSD 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这是我第一次尝试使用 XSD 验证 XML.

Here is my first attempt at validating XML with XSD.

要验证的 XML 文件:

The XML file to be validated:

<?xml version="1.0" encoding="utf-8" ?>
<config xmlns="Schemas" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="config.xsd">
  <levelVariant>
    <filePath>SampleVariant</filePath>
  </levelVariant>
  <levelVariant>
    <filePath>LegendaryMode</filePath>
  </levelVariant>
  <levelVariant>
    <filePath>AmazingMode</filePath>
  </levelVariant>
</config>

XSD,位于Schemas/config.xsd"中,相对于要验证的 XML 文件:

The XSD, located in "Schemas/config.xsd" relative to the XML file to be validated:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="config">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="levelVariant">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="filePath" type="xs:anyURI">
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

现在,我只想准确地验证 XML 文件的当前显示.一旦我更好地理解这一点,我将展开更多.对于像当前存在的 XML 文件这样简单的东西,我真的需要这么多行吗?

Right now, I just want to validate the XML file precisely as it appears currently. Once I understand this better, I'll expand more. Do I really need so many lines for something as simple as the XML file as it currently exists?

C#中的验证代码:

        public void SetURI(string uri)
        {
            XElement toValidate = XElement.Load(Path.Combine(PATH_TO_DATA_DIR, uri) + ".xml");

// begin confusion

       // exception here
       string schemaURI = toValidate.Attributes("xmlns").First().ToString() 
                              + toValidate.Attributes("xsi:noNamespaceSchemaLocation").First().ToString();
        XmlSchemaSet schemas = new XmlSchemaSet();
        schemas.Add(null, schemaURI);

        XDocument toValidateDoc = new XDocument(toValidate);
        toValidateDoc.Validate(schemas, null);
// end confusion

            root = toValidate;
        }

运行上面的代码会出现这个异常:

Running the above code gives this exception:

The ':' character, hexadecimal value 0x3A, cannot be included in a name.

任何照明都将不胜感激.

Any illumination would be appreciated.

推荐答案

而不是使用 XDocument.Validate 扩展方法,我会使用 XmlReader 可以配置为通过 XmlReaderSettings.您可以执行以下代码之类的操作.

Rather than using the XDocument.Validate extension method, I would use an XmlReader which can be configured to process an inline schema via XmlReaderSettings. You could do some thing like the following code.

public void VerifyXmlFile(string path)
{
    // configure the xmlreader validation to use inline schema.
    XmlReaderSettings config = new XmlReaderSettings();
    config.ValidationType = ValidationType.Schema;
    config.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
    config.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
    config.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
    config.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

    // Get the XmlReader object with the configured settings.
    XmlReader reader = XmlReader.Create(path, config);

    // Parsing the file will cause the validation to occur.
    while (reader.Read()) ;

}

private void ValidationCallBack(object sender, ValidationEventArgs vea)
{
    if (vea.Severity == XmlSeverityType.Warning)
        Console.WriteLine(
            "	Warning: Matching schema not found.  No validation occurred. {0}",
            vea.Message);
    else
        Console.WriteLine("	Validation error: {0}", vea.Message);

}

上面的代码假定以下 using 语句.

The code above assumes the following using statements.

using System.Xml;
using System.Xml.Schema;

为了简单起见,我没有返回 boolean 或验证错误集合,您可以轻松地修改它.

Just to keep this simple I did not return a boolean or a collection of validation errors, you could easily modify this to do so.

注意:我修改了您的 config.xml 和 config.xsd 以让它们进行验证.这些是我所做的更改.

Note: I modified your config.xml and config.xsd to get them to validate. These are the changes I made.

config.xsd:

config.xsd:

<xs:element maxOccurs="unbounded" name="levelVariant">

config.xml:

config.xml:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="config.xsd">

这篇关于开始使用 .NET 进行 XSD 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:可以在运行时使用代码针对 xsd 验证 xml 吗? 下一篇:从 MS SQL 数据库获取 XML 架构

相关文章