通过xsd schema结构来验证xml是否合法
import sys
import StringIO
import lxml from lxml import etree
from StringIO import StringIO # Construct XML relevant to the XML schema we're validating against. By altering the string, adding/removing elements
# we can force different errors to occur when validating.
xml = StringIO('''
<CompanyDataRequest xmlns="http://xmlgw.companieshouse.gov.uk" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlgw.companieshouse.gov.uk http://xmlgw.companieshouse.gov.uk/v2-1/schema/CompanyData-v2-2.xsd">
<CompanyNumber>06937730</CompanyNumber>
<CompanyAuthenticationCode>123456</CompanyAuthenticationCode>
<MadeUpDate>2010-06-30x</MadeUpDate>
</CompanyDataRequest>
''') # Clear any previous errors
lxml.etree.clear_error_log() try:
# Get the XML schema to validate against
schema = lxml.etree.XMLSchema(file = 'http://xmlgw.companieshouse.gov.uk/v2-1/schema/CompanyData-v2-2.xsd')
# Parse string of XML
xml_doc = lxml.etree.parse(xml)
# Validate parsed XML against schema returning a readable message on failure
schema.assertValid(xml_doc)
# Validate parsed XML against schema returning boolean value indicating success/failure
print 'schema.validate() returns "%s".' % schema.validate(xml_doc) except lxml.etree.XMLSchemaParseError, xspe:
# Something wrong with the schema (getting from URL/parsing)
print "XMLSchemaParseError occurred!"
print xspe except lxml.etree.XMLSyntaxError, xse:
# XML not well formed
print "XMLSyntaxError occurred!"
print xse except lxml.etree.DocumentInvalid, di:
# XML failed to validate against schema
print "DocumentInvalid occurred!" error = schema.error_log.last_error
if error:
# All the error properties (from libxml2) describing what went wrong
print 'domain_name: ' + error.domain_name
print 'domain: ' + str(error.domain)
print 'filename: ' + error.filename # '<string>' cos var is a string of xml
print 'level: ' + str(error.level)
print 'level_name: ' + error.level_name # an integer
print 'line: ' + str(error.line) # a unicode string that identifies the line where the error occurred.
print 'message: ' + error.message # a unicode string that lists the message.
print 'type: ' + str(error.type) # an integer
print 'type_name: ' + error.type_name
封装类
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Eric.yue import os
import lxml.etree as ET
from StringIO import StringIO
import chardet class R3xmlCheck(object):
def __init__(self, element_xml):
self.elem_xml = element_xml def validate_xsd_xml(self, f_xml, elem_xsd):
try:
elem_xsd = elem_xsd.encode('utf-8')
xsd_doc = StringIO(elem_xsd)
xml_doc = StringIO(f_xml)
xmlschema_doc = ET.parse(xsd_doc)
xmlschema = ET.XMLSchema(xmlschema_doc)
xml = ET.parse(xml_doc)
xmlschema.assertValid(xml)
print 'schema.validate() returns "%s".' % xmlschema.validate(xml) except ET.XMLSchemaParseError, xspe:
# Something wrong with the schema (getting from URL/parsing)
print "XMLSchemaParseError occurred!"
print xspe except ET.XMLSyntaxError, xse:
# XML not well formed
print "XMLSyntaxError occurred!"
print xse except ET.DocumentInvalid, di:
# XML failed to validate against schema
print "DocumentInvalid occurred!" error = xmlschema.error_log.last_error
if error:
# All the error properties (from libxml2) describing what went wrong
print 'domain_name: ' + error.domain_name
print 'domain: ' + str(error.domain)
print 'filename: ' + error.filename # '<string>' cos var is a string of xml
print 'level: ' + str(error.level)
print 'level_name: ' + error.level_name # an integer
print 'line: ' + str(error.line) # a unicode string that identifies the line where the error occurred.
print 'message: ' + error.message # a unicode string that lists the message.
print 'type: ' + str(error.type) # an integer
print 'type_name: ' + error.type_name def run(self):
res = self.validate_xml(self.elem_xml)
if res["result"] is not True:
return res["info"] elem_xsd = self.get_xsd() with open(self.elem_xml) as f:
f_xml = f.read()
chardet_info = chardet.detect(f_xml)
if chardet_info['encoding'] == 'ascii':
f_xml = f_xml.encode('utf-8')
self.validate_xsd_xml(f_xml.strip(),elem_xsd) # matching schemaLocation url
def get_xsd(self):
with open("./xsd/multicacheschemas/MCCI_IN200100UV01.xsd") as f:
elem_xsd = f.read()
return elem_xsd def validate_xml(self, exml):
rinfo = {}
if os.path.exists(exml):
try:
ET.parse(exml)
rinfo['result'] = True
except Exception as err:
rinfo['result'] = False
rinfo['info'] = 'Parsing error info:{0}'.format(err)
return rinfo if __name__ == "__main__":
aa = R3xmlCheck("./xsd/aa.xml")
aa.run()
通过xsd schema结构来验证xml是否合法的更多相关文章
- XSD(XML Schema Definition)用法实例介绍以及C#使用xsd文件验证XML格式
XML Schema 语言也称作 XML Schema 定义(XML Schema Definition,XSD),作用是定义 XML 文档的合法构建模块,类似 DTD,但更加强大. 作用有: ①定义 ...
- 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 ...
- 使用架构(XSD)验证XML文件
假使说XML是一个数据库,那么XSD就是这个数据库的结构.由此可见,XSD是如此重要,如果没有它,我们如何声明以及验证我们需要的XML数据文件的格式和合法性呢?那是不可能完成的任务,如果你将XML数据 ...
- Delphi 7验证XML合法性(利用DTD、XSD)
拥有正确语法的XML被称为“形式良好”的XML.通过DTD验证的XML是“合法”的XML.DTD(文档类型定义)的作用是定义XML 文档的合法构建模块.它使用一系列的合法元素来定义文档结构.XML S ...
- C# xsd 验证 XML数据有效性 问题
使用XSD进行批量数据导入时生成的XML数据有效性这样的功能已经不是第一次做了,之前做的时候都没有碰到什么问题,这些天在开发中遇到了一个很头痛的问题就是无论XSD文件规则怎么写,验证都是通过的. 下面 ...
- C# 利用Xsd验证xml
最近做项目时,用到了xml的序列化与反序列化, 发现最好用xsd来验证xml, 因为反序列化xml不校验xsd. 方法:xmlData变量为xml字符串 MemoryStream ms = new M ...
- C# 使用xsd文件验证XML 格式是否正确
C# 使用xsd文件验证XML 格式是否正确 核心示例代码: //创建xmlDocument XmlDocument doc = new XmlDocument(); //创建声明段 如<?xm ...
- Postman使用tv4进行JSON Schema结构验证和断言
JSON Scheme简介 对于JSON格式的请求数据或者响应数据,在不同的数据和场景下往往会有一部分动态的值及字段.此时我们可以使用JSON Scheme Validator(JSON结构验证)来验 ...
- XSD - <schema> 元素
<schema> 元素 <schema> 元素是每一个 XML Schema 的根元素: <?xml version="1.0"?> <x ...
随机推荐
- HDU 4528 小明系列故事――捉迷藏
广搜. 根据题意,可以知道状态总共有$4*n*m$种.每一个位置四种状态:两个都没有发现:发现$E$没发现$D$:发现$D$没发现$E$:两个都发现. 每次移动的花费都是$1$,队列里面状态的费用是单 ...
- 并查集【p1197】[JSOI2008]星球大战
Description 很久以前,在一个遥远的星系,一个黑暗的帝国靠着它的超级武器统治着整个星系. 某一天,凭着一个偶然的机遇,一支反抗军摧毁了帝国的超级武器,并攻下了星系中几乎所有的星球.这些星球通 ...
- ( 转 ) Mysql group_concat 的反向应用实现(Mysql列转行)
用过Mysql的都知道她有一个很好的实现行转列功能的函数group_concat函数,非常方便 点击(此处)折叠或打开 SELECT * FROM group_test; SELECT id, GRO ...
- [PKUSC2018]神仙的游戏(FFT)
给定一个01?串,对所有len询问是否存在一种填法使存在长度为len的border. 首先有个套路的性质:对于一个长度为len的border,这个字符串一定有长度为n-len的循环节(最后可以不完整) ...
- UVA 10160 Servicing Stations(状态压缩+迭代加深)
[题目链接] LInk [题目大意] 给出一些点和边,选择一个点就能把这个点和相邻的点都覆盖,求最小点覆盖 [题解] 我们压缩点被覆盖的状态,迭代加深搜索覆盖的最小点数, 当剩余的点全部选上时都无法完 ...
- 【强联通分量缩点】【搜索】bzoj2208 [Jsoi2010]连通数
两次dfs缩点,然后n次dfs暴搜. #include<cstdio> #include<vector> #include<cstring> using names ...
- 1.6(学习笔记)Session
一. Session简介 Session是用于解决HTTP无状态问题,HTTP协议本身是没有状态的, 就类似一个没有记性的商人,每次只交易当前的货物,交易完后就忘记了 以前的交易历史.我们和商人交易时 ...
- 《深入理解Spark-核心思想与源码分析》(三)第三章SparkContext的初始化
3.1 SparkContext概述 SparkConf负责配置参数,主要通过ConcurrentHaspMap来维护各种Spark的配置属性. class SparkConf(loadDefault ...
- NEXUS7 学习
一.编译环境搭建 (更细节的环境搭建请参考:How to Build CyanogenMod for Nexus 7 (Wi-Fi, 2012 version) (codename: grouper) ...
- Session集中式管理
Asp.net Session集中式管理主要有StateServer(状态服务器).Sqlserver(数据库服务器).自定义(如Redis缓存服务器)等,本文主要介绍StateServe ...