且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用XML Schema验证XML数据输入

更新时间:2021-10-17 19:10:25

现在XML使用的越来越多,在SQL Server表中我们可以创建XML列存储数据。 昨天在论坛看到有人说创建了一个存储过程处理XML,但是插入目标表的时候报错,而报的错误不详细。 其实这个问题的根本原因是XML的数据有问题,应该在插入的时候对输入的数据进行验证(对于用户输入的数据一定要做验证)。

 

其实SQL Server已经提供了XML Schema验证,下面我们看一个例子:

 

--创建XML Schema Collation

CREATE XML SCHEMA COLLECTION myCollection AS

'<xsd:schemaxmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns="http://myBooks"

elementFormDefault="qualified"

targetNamespace="http://myBooks">

<xsd:element name="bookstore"type="bookstoreType" />

<xsd:complexTypename="bookstoreType">

<xsd:sequencemaxOccurs="unbounded">

<xsd:element name="book"type="bookType" />

</xsd:sequence>

</xsd:complexType>

<xsd:complexType name="bookType">

<xsd:sequence>

<xsd:element name="title"type="xsd:string" />

<xsd:element name="author"type="authorName" />

<xsd:element name="price"type="xsd:decimal" />

</xsd:sequence>

<xsd:attribute name="genre"type="xsd:string" />

<xsd:attributename="publicationdate" type="xsd:string" />

<xsd:attribute name="ISBN"type="xsd:string" />

</xsd:complexType>

<xsd:complexTypename="authorName">

<xsd:sequence>

<xsd:elementname="first-name" type="xsd:string" />

<xsd:element name="last-name"type="xsd:string" />

</xsd:sequence>

</xsd:complexType>

</xsd:schema>'

 

 

--创建表用上面创建的XML Schema做验证

create table XmlCatalog ( IDint, MyInfoXML(CONTENT myCollection));

 

--插入数据

INSERT XmlCatalogVALUES(1,'<?xmlversion="1.0"?>

<bookstorexmlns="http://myBooks">

<book genre="autobiography"publicationdate="1981"

ISBN="1-861003-11-0">

<title>The Autobiography of BenjaminFranklin</title>

<author>

<first-name>Benjamin</first-name>

<last-name>Franklin</last-name>

</author>

<price>8.99</price>

</book>

<book genre="novel"publicationdate="1967"

ISBN="0-201-63361-2">

<title>The ConfidenceMan</title>

<author>

<first-name>Herman</first-name>

<last-name>Melville</last-name>

</author>

<price>11.99</price>

</book>

<book genre="philosophy"publicationdate="1991"

ISBN="1-861001-57-6">

<title>The Gorgias</title>

<author>

<first-name>Sidas</first-name>

<last-name>Plato</last-name>

</author>

<price>9.99</price>

</book>

</bookstore>

')

 

 

 

--如果XML格式有问题报错

INSERT XmlCatalogVALUES(1,'<?xmlversion="1.0"?>

<book genre="philosophy"publicationdate="1991"

ISBN="1-861001-57-6">

<title>The Gorgias</title>

<author>

<first-name>Sidas</first-name>

<last-name>Plato</last-name>

</author>

<price>9.99</price>

</book>

</bookstore>

')

 

 

Msg 6913, Level 16, State 1, Line 1

XML Validation: Declaration not found for element 'book'.Location: /*:book[1]

 

这样的错误是非常清楚的,可以很快的帮助我们Troubleshooting.


本文转自 lzf328 51CTO博客,原文链接:http://blog.51cto.com/lzf328/968386