开始了解.NET XSD验证 [英] Getting started with XSD validation with .NET

查看:155
本文介绍了开始了解.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,位于架构/ 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 扩展方法,我会用一个可通过 XmlReaderSettings 的被配置为处理内联架构的XmlReader 。你可以做类似下面的代码的一些事情。

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(
            "\tWarning: Matching schema not found.  No validation occurred. {0}",
            vea.Message);
    else
        Console.WriteLine("\tValidation error: {0}", vea.Message);

}



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

The code above assumes the following using statements.

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



只是为了保持这个简单的我没有回布尔或验证错误的集合,你可以很容易地修改该这样做。

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验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆