使用xsd验证xml格式的正确性

使用xsd验证xml格式的正确性3 该方式验证 xml 格式正确性 轻代码重 xsd 配置 但也有好处 当 xml 格式发生改变时 无需修改代码 只需要对应修改 xsd 即可 且相对代码来说 易上手

大家好,欢迎来到IT知识分享网。

1.1 基础知识介绍

  • XML简介:XML是可扩展标记语言(eXtensible Markup Language)的缩写,它是一种数据表示格式,可以描述非常复杂的数据结构,常用于传输和存储数据。xml文件、xml消息。
  • XSD简介:是XML Schema Description的缩写,描述XML的结构,以验证XML是否符合要求。编写直接使用xml语言,无需学习新语言,描述了可能出现的元素、属性和值等。

1.2 XSD的核心组件

元素和属性定义:如何定义元素和属性,包括简单类型和复杂类型。

  • element – 定义普通元素,类型为内置类型(xs:string\xs:date\xs:decimal\xs:integer\xs:boolean\xs:time)
  • simpleType – 在普通类型基础上,有其余额外的格式要求(通过xs:restriction来限定,后面会详细说明限定如何设置)
  • complexType – 含有多个子元素(xs:sequence–子元素必须按顺序出现,默认只出现一次,可通过minOccurs/maxOccurs设置出现次数)

student.xml:

<students> <class>Grade one of high school</class> <student> <name>test1</name> <age>16</age> </student> <student> <name>test2</name> <age>15</age> </student> </students> 
<?xml version="1.0" encoding='utf-8'?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="students"> <xs:complexType> <xs:sequence> <xs:element name="class" type="xs:string"/> <xs:element name='student' maxOccurs='unbounded'> <xs:complexType> <xs:sequence> <xs:element name='name'> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value='test\d{1,}'/> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="age" type="xs:integer"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> 
  • 模型组:介绍xs:sequence, xs:choice, xs:all等模型组的使用和区别。
    • xs:sequence:用于定义一组元素,这些元素必须按照在 xs:sequence 中声明的顺序出现在XML文档中。
    • xs:choice:允许在其子元素中选择一个出现。只能选择其中一个。
    • xs:all:允许其子元素以任何顺序出现,每个元素最多出现一次。这适用于元素的顺序不重要的情况。但子元素不能是复杂元素。
  • 数据类型:内置数据类型和用户自定义数据类型的使用。
    • 常用的内置数据类型:
      • xs:string
      • xs:decimal
      • xs:integer
      • xs:boolean
      • xs:date
      • xs:time
    • 用户自定义类型:xs:restriction限定。
      • enumeration 定义可接受值列表
<?xml version="1.0" encoding='utf-8'?> <!-- 性别元素的值只能是男或女 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="gender"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value=''/> <xs:enumeration value=''/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 
  • fractionDigits 指定允许的最大小数位数。必须大于或等于零
<?xml version="1.0" encoding='utf-8'?> <!-- 体重元素,最多2位小数位 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name='weight'> <xs:simpleType> <xs:restriction base='xs:decimal'> <xs:fractionDigits value='2'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 
  • length 指定允许的精确字符数或列表项数。必须大于或等于零
<?xml version="1.0" encoding='utf-8'?> <!-- 学号元素,长度必须为10位数 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name='studentid'> <xs:simpleType> <xs:restriction base="xs:string"> <xs:length value='10'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 
  • maxExclusive 指定数值的上界(值必须小于此值)
<?xml version="1.0" encoding='utf-8'?> <!-- 分数元素,最大值为150,整数位至少1位,至多3位,小数位至多2位,小数位可以没有 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name='score'> <xs:simpleType> <xs:restriction base="xs:decimal"> <xs:maxExclusive value='151'/> <xs:pattern value='\d{1,3}.?\d{0,2}'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 
  • maxInclusive 指定数值的上限(值必须小于或等于此值)
<?xml version="1.0" encoding='utf-8'?> <!-- 分数元素,最大值为150,整数位至少1位,至多3位,小数位至多2位,小数位可以没有 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name='score'> <xs:simpleType> <xs:restriction base="xs:decimal"> <xs:maxInclusive value='150'/> <xs:pattern value='\d{1,3}.?\d{0,2}'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 
  • maxLength 指定允许的最大字符数或列表项数。必须大于或等于零
<?xml version="1.0" encoding='utf-8'?> <!-- 座右铭元素,最长字符数限制为100字符 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name='motto'> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value='100'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 
  • minExclusive 指定数值的下界(值必须大于此值)
<?xml version="1.0" encoding='utf-8'?> <!-- 分数元素,最小值为0,最大值为150,整数位至少1位,至多3位,小数位至多2位,小数位可以没有 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name='score'> <xs:simpleType> <xs:restriction base="xs:decimal"> <xs:minExclusive value='-1'/> <xs:maxInclusive value='150'/> <xs:pattern value='\d{1,3}.?\d{0,2}'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 
  • minInclusive 指定数值的下限(值必须大于或等于此值)
<?xml version="1.0" encoding='utf-8'?> <!-- 分数元素,最小值为0,最大值为150,整数位至少1位,至多3位,小数位至多2位,小数位可以没有 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name='score'> <xs:simpleType> <xs:restriction base="xs:decimal"> <xs:minInclusive value='0'/> <xs:maxInclusive value='150'/> <xs:pattern value='\d{1,3}.?\d{0,2}'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 
  • minLength 指定允许的最小字符数或列表项数。必须大于或等于零
<?xml version="1.0" encoding='utf-8'?> <!-- 座右铭元素,最短为1个字符,最长字符数限制为100字符 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name='motto'> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value='1'/> <xs:maxLength value='100'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 
  • pattern 定义可接受的确切字符序列
<?xml version="1.0" encoding='utf-8'?> <!-- 性别元素的值只能是男或女 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="gender"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value='[男|女]'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 
  • totalDigits 指定允许的精确数字数。必须大于零
<?xml version="1.0" encoding='utf-8'?> <!-- 年龄元素的值数字为2位 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="age"> <xs:simpleType> <xs:restriction base="xs:integer"> <xs:totalDigits value='2'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 
  • whiteSpace 指定如何处理空白字符(换行符、制表符、空格和回车),有三个可能的值:
      1. preserve:保留所有空白字符。这是默认行为,如果不指定 whiteSpace,则XML解析器会保留输入中的所有空白。
      1. replace:将所有空白字符替换为普通空格。这包括将制表符、换行符和回车符替换为空格。
      1. collapse:首先将所有空白字符替换为普通空格,然后合并连续的空格为一个空格,并删除字符串开头和结尾的空格。
<?xml version="1.0" encoding='utf-8'?> <!-- 座右铭元素,最短为1个字符,最长字符数限制为100字符,并且限定前后不能有空格,中间不能换行 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name='motto'> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value='1'/> <xs:maxLength value='100'/> <xs:whiteSpace value='collapse'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema> 

1.3 高级XSD特性

继承和多态:使用xs:extension和xs:restriction进行类型扩展和限制。

  • xs:extension:在基础类型上新增新的元素。eg: 在基础c_student类型上,新增gender元素。
<?xml version="1.0" encoding='utf-8'?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="c_student"> <xs:sequence> <xs:element name='name'> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value='test\d{1,}'/> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="age" type="xs:integer"/> </xs:sequence> </xs:complexType> <xs:element name='student'> <xs:complexType> <xs:complexContent> <xs:extension base='c_student'> <xs:sequence> <xs:element name="gender"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value='[男|女]'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema> 
  • xs:restriction:修改已存在的元素的值,必须重新对所有元素定义。eg: 对基础类型c_student的age设置默认值16.
<?xml version="1.0" encoding='utf-8'?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="c_student"> <xs:sequence> <xs:element name='name'> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value='test\d{1,}'/> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="age" type="xs:integer"/> </xs:sequence> </xs:complexType> <xs:element name='student'> <xs:complexType> <xs:complexContent> <xs:restriction base='c_student'> <xs:sequence> <xs:element name='name'> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value='test\d{1,}'/> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="age" type="xs:integer" default='16'/> </xs:sequence> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> </xs:schema> 
  • 文件引用:xs:import 和xs:include进行文件间的引用。
    • xs:include:命名空间相同的两个文件,可以使用include引用另一个xsd文件的定义元素和类型。

base.xsd

<?xml version="1.0" encoding='utf-8'?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace='basic.type'> <xs:simpleType name="t_name"> <xs:restriction base="xs:string"> <xs:pattern value='test\d{1,}'/> </xs:restriction> </xs:simpleType> <xs:simpleType name="t_gender"> <xs:restriction base="xs:string"> <xs:enumeration value=''/> <xs:enumeration value=''/> </xs:restriction> </xs:simpleType> <xs:simpleType name='t_studentid'> <xs:restriction base="xs:string"> <xs:length value='10'/> </xs:restriction> </xs:simpleType> <xs:simpleType name='t_motto'> <xs:restriction base="xs:string"> <xs:minLength value='1'/> <xs:maxLength value='100'/> <xs:whiteSpace value='collapse'/> </xs:restriction> </xs:simpleType> <xs:simpleType name="t_age"> <xs:restriction base="xs:integer"> <xs:totalDigits value='2'/> </xs:restriction> </xs:simpleType> </xs:schema> 

fat_student.xsd:命名空间设置成和basic.xsd一致。与base.xsd放在同一目录下。

<?xml version="1.0" encoding='utf-8'?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:prd='basic.type' targetNamespace='basic.type'> <xs:include schemaLocation="base.xsd"/> <xs:element name="students"> <xs:complexType> <xs:sequence> <xs:element name="student" maxOccurs='unbounded'> <xs:complexType> <xs:sequence> <xs:element name="name" type="prd:t_name"/> <xs:element name='age' type="prd:t_age"/> <xs:element name='studentid' type="prd:t_studentid"/> <xs:element name='gender' type="prd:t_gender"/> <xs:element name='motto' type="prd:t_motto"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> 
  • xs:import:命名空间不相同的两个文件,可以使用import引用,并使用namespace指明引用文件的命名空间名。

fat_student2.xsd:不指定该xsd的命名空间或命名空间设置成和base.xsd不一致。与base.xsd放在同一目录下。

<?xml version="1.0" encoding='utf-8'?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:prd='basic.type'> <xs:import namespace='basic.type' schemaLocation='base.xsd'/> <xs:element name="students"> <xs:complexType> <xs:sequence> <xs:element name="student" maxOccurs='unbounded'> <xs:complexType> <xs:sequence> <xs:element name="name" type="prd:t_name"/> <xs:element name='age' type="prd:t_age"/> <xs:element name='studentid' type="prd:t_studentid"/> <xs:element name='gender' type="prd:t_gender"/> <xs:element name='motto' type="prd:t_motto"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> 

注:如果需要引入多个xsd,可以加多几个include或import节点。

1.4 python中使用XSD验证XML

1.4.1 传入xml文件的路径:

import lxml.etree as ET def validateXMLByXSD(file_xml, file_xsd): """ Verify that the XML compliance with XSD Arguments: 1. file_xml: Input xml file 2. file_xsd: xsd file which needs to be validated against xml Return: No return value """ try: print("Validating:{0}".format(file_xml)) print("xsd_file:{0}".format(file_xsd)) xml_doc = ET.parse(file_xml) xsd_doc = ET.parse(file_xsd) xmlschema = ET.XMLSchema(xsd_doc) xmlschema.assert_(xml_doc) return True except ET.XMLSyntaxError as err: print("PARSING ERROR:{0}".format(err)) return False except AssertionError as err: print("Incorrect XML schema: {0}".format(err)) return False if __name__ == '__main__': print(validateXMLByXSD('xml文件路径', 'xsd文件路径')) 

1.4.2 传入xml字符串:

import lxml.etree as ET def validateXMLByXSD(str_xml, file_xsd): """ Verify that the XML compliance with XSD Arguments: 1. str_xml: Input xml string 2. file_xsd: xsd file which needs to be validated against xml Return: No return value """ try: print("Validating:{0}".format(str_xml)) print("xsd_file:{0}".format(file_xsd)) xml_doc = ET.fromstring(str_xml) xsd_doc = ET.parse(file_xsd) xmlschema = ET.XMLSchema(xsd_doc) xmlschema.assert_(xml_doc) return True except ET.XMLSyntaxError as err: print("PARSING ERROR:{0}".format(err)) return False except AssertionError as err: print("Incorrect XML schema: {0}".format(err)) return False if __name__ == '__main__': print(validateXMLByXSD('xml字符串', 'xsd文件路径')) 

1.5 实战演练

①使用student.xsd验证student.xml的正确性:

  • 不修改上述student.xml和student.xsd文件内容,直接使用1.4.1中代码验证。
    在这里插入图片描述
  • 修改student.xml文件内容age为非数字:
    在这里插入图片描述
  • 删掉student.xsd中maxOccurs的配置,故student元素仅能出现一次:
    在这里插入图片描述

②使用fat_student2.xsd验证student2.xml的正确性:

student2.xml

<students> <student> <name>test1</name> <age>16</age> <studentid></studentid> <gender></gender> <motto>努力会有回报的。</motto> </student> <student> <name>test2</name> <age>17</age> <studentid></studentid> <gender></gender> <motto>勤奋。</motto> </student> </students> 

在这里插入图片描述

其他:

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/122377.html

(0)
上一篇 2025-10-17 09:26
下一篇 2025-10-17 09:45

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信