C# XML XSD CS 转换以及验证


XML 文件

<?xml version="1.0"?>
<CustomerMappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Mappings>
    <CustomerMapping ColumnName="Customer" MappingName="Customer" />
    <CustomerMapping ColumnName="TypeofBusiness" MappingName="2" />
    <CustomerMapping ColumnName="Name" MappingName="3" />
    <CustomerMapping ColumnName="Name2" MappingName="4" />
    <CustomerMapping ColumnName="City" MappingName="5" />
    <CustomerMapping ColumnName="Street" MappingName="6" />
    <CustomerMapping ColumnName="PostlCode" MappingName="7" />
    <CustomerMapping ColumnName="Telephone" MappingName="8" />
    <CustomerMapping ColumnName="Region" MappingName="9" />
    <CustomerMapping ColumnName="SubRegion" MappingName="10" />
    <CustomerMapping ColumnName="Province" MappingName="11" />
    <CustomerMapping ColumnName="Prov" MappingName="12" />
    <CustomerMapping ColumnName="LocationId" MappingName="13" />
  </Mappings>
</CustomerMappings>

通过 XML 生成 XSD 文件

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="CustomerMappings" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="CustomerMappings" msdata:IsDataSet="true" msdata:Locale="en-US">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Mappings">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="CustomerMapping" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                  <xs:attribute name="ColumnName" type="xs:string" />
                  <xs:attribute name="MappingName" type="xs:string" />
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

通过 XSD 生成 CS 文件

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18063
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.0.30319.1.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class CustomerMappings {

    private CustomerMappingsMappings[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Mappings", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public CustomerMappingsMappings[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CustomerMappingsMappings {

    private CustomerMappingsMappingsCustomerMapping[] customerMappingField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("CustomerMapping", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public CustomerMappingsMappingsCustomerMapping[] CustomerMapping {
        get {
            return this.customerMappingField;
        }
        set {
            this.customerMappingField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CustomerMappingsMappingsCustomerMapping {

    private string columnNameField;

    private string mappingNameField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string ColumnName {
        get {
            return this.columnNameField;
        }
        set {
            this.columnNameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string MappingName {
        get {
            return this.mappingNameField;
        }
        set {
            this.mappingNameField = value;
        }
    }
}

验证方法

string xmlFile = @"D:\Lance\Study\Mapping.xml";
string xsdFile = @"D:\Lance\Study\Mapping.xsd";

var xsdValidateResult = ValidateXml(xmlFile, xsdFile);

if (xsdValidateResult.Item1)
{
    Console.WriteLine("校验通过!");
}
else
{
    Console.WriteLine("校验失败,原因:\n" + xsdValidateResult.Item2);
}


/// <summary>
/// 使用xsd验证xml是否正确
/// </summary>
/// <param name="xmlFilePath">xml文件路径</param>
/// <param name="xsdFilePath">xsd文件路径</param>
/// <returns></returns>
static Tuple<bool, string> ValidateXml(string xmlFilePath, string xsdFilePath)
{
    Tuple<bool, string> result = new Tuple<bool, string>(true, "");
    XmlReaderSettings st = new XmlReaderSettings();
    st.ValidationType = ValidationType.Schema;
    st.Schemas.Add(null, xsdFilePath);

    //设置验证xml出错时的事件。
    st.ValidationEventHandler += (obj, e) =>
    {
        result = new Tuple<bool, string>(false, e.Message);
    };

    XmlReader xr = XmlReader.Create(xmlFilePath, st);
    while (xr.Read())
    {
        if (xr.IsStartElement())
        {
            xr.Read();
        }
    }
    xr.Close();
    return result;
}

知识共享许可协议
《C# XML XSD CS 转换以及验证》 常伟华 创作。
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议 | 3.0 中国大陆许可协议进行许可。

站内公告

A PHP Error was encountered

Severity: Core Warning

Message: PHP Startup: zip: Unable to initialize module Module compiled with module API=20060613 PHP compiled with module API=20090626 These options need to match

Filename: Unknown

Line Number: 0

Backtrace: