被插入部分中的XML无效字符,会被转换成实体,如“<”保存为<。下面的插入CDATA部分后XML文档的内容:
<root> <item ID="1"> <title>Ajax实战</title> <author>张洪举</author> </item> <item ID="2"> <title>ASP.NET实战</title> <author>卢桂章</author> <desc> <送货方式>上门<价款>未收</desc> </item> </root>
(6)插入文本节点
要将文件插入到XML中,需要使用text函数构造文本,参考下面的示例:
DECLARE @myDoc xml
SET @myDoc = '<root>
<item ID="1">
<title>Ajax实战</title>
<author>张洪举</author>
</item>
</root>'
SET @myDoc.modify('
insert text{"订单列表"}
as first into (/root)[1]');
SELECT @myDoc
GO
得到的XML结果如下:
<root>订单列表<item ID="1"><title>Ajax实战</title><author>张洪举</author></item></root>
(7)将节点插入类型化的xml列中
在下面的示例中,首先创建了一个架构集合,并建立了一个使用该架构集合的表。在使用Transact-SQL INSERT语句向表中插入一个符合架构约束的XML后,再使用XML DML insert向该XML中插入一个item节点。
-- 创建XML架构集合
CREATE XML SCHEMA COLLECTION MySchemas
AS
N'<?xml version = "1.0"?>
<xsd:schema targetNamespace="http://schemas.mybook.com/customerschemas"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="customer">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="item">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="customername" type="xsd:string"/>
<xsd:element name="address" type="xsd:string"/>
<xsd:element name="phone" type="xsd:string"/>
<xsd:element name="contact" type="xsd:string"/>
</xsd:sequence>
<xsd:attribute name="ID" type="xsd:int"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>';
GO
-- 创建包含xml数据类型列的表
CREATE TABLE MyCustomer
(CustomerID int IDENTITY PRIMARY KEY,
CustomerItem xml(MySchemas));
GO
-- 向表中插入XML,该XML应当符合http://schemas.mybook.com/customerschemas命名空间架构的定义
INSERT INTO MyCustomer
VALUES
(N'<C:customer xmlns:C="http://schemas.mybook.com/customerschemas">
<item ID="1">
<customername>北方书城</customername>
<address>北京市海淀区知春路22号</address>
<phone>2222222</phone>
<contact>刘先生</contact>
</item>
</C:customer>');
-- 使用XML DML insert插入另一个item节点到XML中
UPDATE MyCustomer
SET CustomerItem.modify('
declare namespace CS="http://schemas.mybook.com/customerschemas";
insert (<item ID="2">
<customername>东图大厦</customername>
<address>长春市朝阳大街99号</address>
<phone>1111111</phone>
<contact>孙小姐</contact>
</item>)
into (/CS:customer)[1] ')
WHERE CustomerID=1;
SELECT CustomerItem
FROM Mycustomer;
GO
评论加载中…
![]() |