使用XML Schema验证XML数据输入

本文介绍如何使用SQL Server的XML Schema校验功能确保XML数据的有效性。通过创建XML Schema Collection并将其应用于表中的XML列,可以避免因数据格式错误导致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在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( ID int, 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值