很早以前看过一句话:“XML就象空气”,在企业应用开发中XML是一个重要的数据交换标准。而XSD则可以用来校验XML的数据格式是否正确。

一个典型的XSD文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSpy v2013 (http://www.altova.com) by () -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="AWB">
<xs:annotation>
<xs:documentation>运单</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="AWB-INFO" minOccurs="1" maxOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="AWBPRE">
<xs:annotation>
<xs:documentation>运单前缀只有输入3位数字</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:positiveInteger">
<xs:totalDigits value="3"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="AWBNO">
<xs:annotation>
<xs:documentation>运单号只能输入8位数字</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:positiveInteger">
<xs:totalDigits value="8"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="PART-INFO">
<xs:complexType>
<xs:sequence>
<xs:element name="PARTICIPANT" minOccurs="2" maxOccurs="unbounded">
<xs:annotation>
<xs:documentation>物流参与者至少要有2个</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="TYPE">
<xs:annotation>
<xs:documentation>物流参考者类型,只能是A/S/C其中之一</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="C"/>
<xs:enumeration value="S"/>
<xs:enumeration value="A"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="ADDRESS" type="AddressType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="AddressType">
<xs:sequence>
<xs:element name="Name" type="xs:string"/>
<xs:element name="Street" type="xs:string"/>
<xs:element name="City" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

看到这一大段xml,第一反应通常是头晕,幸好这些内容不用纯手动编写,已经有很多现成的工具,比如XmlSpy可以方便的以GUI方式,通过轻点鼠标,拖拖拉拉就能完成XSD的开发。

这是XmlSpy中XSD的可视化设计界面,还能切换不同的视图,比如下面这样:

对于首次接触XmlSpy的朋友,强烈推荐看下安装目录下的Tutorial.pdf,这是一个不错的入门教程,30分钟以前绝对可以快速浏览一遍。

C#中可以方便的使用XSD来验证xml文件的正确性,示例代码如下:

using System;
using System.Xml; namespace XsdValidate
{
class Program
{
static void Main(string[] args)
{
string xmlFile = @"C:\Users\jimmy.yang\Desktop\XMLSPY\TEST\sample.xml";
string xsdFile = @"C:\Users\jimmy.yang\Desktop\XMLSPY\TEST\sample.xsd"; var xsdValidateResult = ValidateXml(xmlFile, xsdFile); if (xsdValidateResult.Item1)
{
Console.WriteLine("校验通过!");
}
else
{
Console.WriteLine("校验失败,原因:\n" + xsdValidateResult.Item2);
}
Console.Read(); } /// <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;
}
}
}

注意:如果节点采用pattern,即正则表达式验证,比如

<xs:restriction base="xs:string">
         <xs:pattern value="^\d{8}$"></xs:pattern>
</xs:restriction>

XMLSpy中,该节点必须填写"^12345678$"才能验证通过,而如果用.NET/JAVA写代码验证的话,^、$能自动识别为"匹配字符开头/结尾"

XSD还能方便的生成c#类,有二种方法:

1、XMLSpy里先打开一个XSD文件,然后 DTD/Schema->Generate Program Code,接下来按提示操作即可

注:XMLSpy生成的c#类太过于复杂,我个人觉得有点啰嗦

2、直接使用vs.net自带的xsd命令

vs.net命令行下,输入

xsd "xsd文件所在的路径" /classes /out:"cs文件的输出目录"

即可生成对应的cs类 ,文中最开头的xsd生成的cs类代码如下:

//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18331
//
// 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 AWB { private AWBAWBINFO aWBINFOField; private AWBPARTICIPANT[] pARTINFOField; /// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("AWB-INFO")]
public AWBAWBINFO AWBINFO {
get {
return this.aWBINFOField;
}
set {
this.aWBINFOField = value;
}
} /// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute("PART-INFO")]
[System.Xml.Serialization.XmlArrayItemAttribute("PARTICIPANT", IsNullable=false)]
public AWBPARTICIPANT[] PARTINFO {
get {
return this.pARTINFOField;
}
set {
this.pARTINFOField = 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 AWBAWBINFO { private string aWBPREField; private string aWBNOField; /// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="positiveInteger")]
public string AWBPRE {
get {
return this.aWBPREField;
}
set {
this.aWBPREField = value;
}
} /// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="positiveInteger")]
public string AWBNO {
get {
return this.aWBNOField;
}
set {
this.aWBNOField = value;
}
}
} /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class AddressType { private string nameField; private string streetField; private string cityField; /// <remarks/>
public string Name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
} /// <remarks/>
public string Street {
get {
return this.streetField;
}
set {
this.streetField = value;
}
} /// <remarks/>
public string City {
get {
return this.cityField;
}
set {
this.cityField = 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 AWBPARTICIPANT { private AWBPARTICIPANTTYPE tYPEField; private AddressType aDDRESSField; /// <remarks/>
public AWBPARTICIPANTTYPE TYPE {
get {
return this.tYPEField;
}
set {
this.tYPEField = value;
}
} /// <remarks/>
public AddressType ADDRESS {
get {
return this.aDDRESSField;
}
set {
this.aDDRESSField = value;
}
}
} /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public enum AWBPARTICIPANTTYPE { /// <remarks/>
C, /// <remarks/>
S, /// <remarks/>
A,
}

xsd命令还能直接根据xml生成xsd文件,使用方法如下:

xsd c:\sampe.xml /out:c:\

这样会根据sample.xml在c:\生成sample.xsd文件

作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com 
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

XmlSpy / XSD以及验证的更多相关文章

  1. XmlSpy / XSD 以及 验证

    很早以前看过一句话:“XML就象空气”,在企业应用开发中XML是一个重要的数据交换标准.而XSD则可以用来校验XML的数据格式是否正确. 一个典型的XSD文件如下: <?xml version= ...

  2. XSD(XML Schema Definition)用法实例介绍以及C#使用xsd文件验证XML格式

    XML Schema 语言也称作 XML Schema 定义(XML Schema Definition,XSD),作用是定义 XML 文档的合法构建模块,类似 DTD,但更加强大. 作用有: ①定义 ...

  3. C# 使用xsd文件验证XML 格式是否正确

    C# 使用xsd文件验证XML 格式是否正确 核心示例代码: //创建xmlDocument XmlDocument doc = new XmlDocument(); //创建声明段 如<?xm ...

  4. 28.XSD(XML Schema Definition)用法实例介绍以及C#使用xsd文件验证XML格式

    转自https://www.cnblogs.com/gdjlc/archive/2013/09/08/3308229.html XML Schema 语言也称作 XML Schema 定义(XML S ...

  5. DELPHI中调用XSD去验证XML的合法性

    procedure TFrmPrintReport.Button3Click(Sender: TObject);var  SchemaDoc, XmlDoc: IXMLDOMDocument2;  S ...

  6. XML的应用 ---- 从一个范例看xml数据、xsd验证、xslt样式

    从一个范例看XML的应用 引言 如果你已经看了Asp.Net Ajax的两种基本开发模式 这篇文章,你可能很快会发现这样一个问题:在那篇文章的方式2中,客户端仅仅是发送了页面上一个文本框的内容到服务端 ...

  7. C# 利用Xsd验证xml

    最近做项目时,用到了xml的序列化与反序列化, 发现最好用xsd来验证xml, 因为反序列化xml不校验xsd. 方法:xmlData变量为xml字符串 MemoryStream ms = new M ...

  8. 如何由XSD自动生成XML和实体类

    项目中有时候要用XML作为数据源,因此需要定义XML文件和相应的类,最佳方法是首先定义XSD,然后自动生成实体类,最后生成XML和填充数据:读取XML数据源的时候,首先用XSD验证XML数据格式,然后 ...

  9. Java使用Schema模式对XML验证

    XML允许创作者定义自己的标签,因其灵活的特性让其难以编写和解析.因此必须使用某种模式来约束其结构.目前最流行的这种模式有两种:DTD和SCHEMA,而后者以其独特的优势即将取代DTD模式,目前只是过 ...

随机推荐

  1. EF数据库优先模式(三)

    今天2018年4月1日,呼叫王伟,81192,收到请返航! 接上次说,本节将LINQ以及lambda表达式 LINQ是C#里面针对SQL Server特有的数据访问操作方法,通俗一点说就是类似于写SQ ...

  2. 微信小程序 发现之旅(二)—— 自定义组件

    组件化的项目开发中,组件应当划分为三个层次:组件.模块.页面 微信小程序已经为开发者封装好了基础组件,页面文件(pages)也有了详细的规定 而模块就需要自行开发,并且要和页面文件区分开,这就涉及到自 ...

  3. javascript:this指向

    this常见指向问题 this的用法 1.直接在函数中使用 谁调用这个函数this就指向谁 2.对象中使用, 一般情况下指向该对象 3.在构造函数中使用 改变this的指向,两种方法的作用都是相同的, ...

  4. gis cad导出弧段在arcmap下 不准问题

    我发现cad 的图形导出到arcmap下会出现各种各样的丢失问题,特别是cad的弧段在arcmap下会弯曲(弧度指向另外一边). 那么应该怎么解决这个问题呢?后来想到FME可以高效的还原cad的图形, ...

  5. Android Studio离线打包5+SDK

    dcloud官网下载最新版5+SDK 解压后,Android Studio导入HBuilder-Hello,选择From eclispe 修改assets/data/dcloud_control.xm ...

  6. 关于win10下JDK环境变量的配置以及关于JDK的一些说明

    一.JDK的下载和安装 这里提供32位和64位JDK的下载链接 百度网盘:https://pan.baidu.com/s/1xtiVOE2gPCvlGCTy0vfBaw 密码:c5m4   官网:ht ...

  7. 机器学习实战(Machine Learning in Action)学习笔记————09.利用PCA简化数据

    机器学习实战(Machine Learning in Action)学习笔记————09.利用PCA简化数据 关键字:PCA.主成分分析.降维作者:米仓山下时间:2018-11-15机器学习实战(Ma ...

  8. cuda中当数组数大于线程数的处理方法

    参考stackoverflow一篇帖子的处理方法:https://stackoverflow.com/questions/26913683/different-way-to-index-threads ...

  9. Jboss7.1 local EJB lookup problem

    We are trying to lookup for an Local EJB in JBoss7.1, but we get an ClassCast Exception. This local ...

  10. 数据仓库四个特点(面向主题的(Subject Oriented)、集成的(Integrate)、相对稳定的(Non-Volatile)、反映历史变化(Time Variant))

    1.面向主题. 数据仓库中的数据是按照一定的主题域进行组织. 主题是一个抽象的概念,是指用户使用数据仓库进行决策时所关心的重点方面,一个主题通常与多个操作型信息系统相关.而操作型数据库的数据组织面向事 ...