在SQL Server中使用XML数据

XML (eXtensible Markup Language) is one of the most common formats used to share information between different platforms. Owing to its simplicity and readability, it has become the de-facto standard for data sharing. In addition, XML is easily extendable.

XML(可扩展标记语言)是用于在不同平台之间共享信息的最常见格式之一。 由于其简单性和可读性,它已成为数据共享的实际标准。 另外,XML易于扩展。

In this article, we will see how we can work with XML in SQL Server. We will see how to convert tables in SQL into XML, how to load XML documents into SQL Server and how to create SQL tables from XML documents.

在本文中,我们将看到如何在SQL Server中使用XML。 我们将看到如何将SQL中的表转换为XML,如何将XML文档加载到SQL Server中以及如何从XML文档创建SQL表。

Let’s first generate some dummy data. We will use this data to create XML documents. Execute the following script:

让我们首先生成一些虚拟数据。 我们将使用此数据来创建XML文档。 执行以下脚本:

CREATE DATABASE Showroom
 
Use Showroom
CREATE TABLE Car  
(  
  CarId int identity(1,1) primary key,  
  Name varchar(100),  
  Make varchar(100),  
  Model int ,  
  Price int ,  
  Type varchar(20)  
)  
    
insert into Car( Name, Make,  Model , Price, Type)
VALUES ('Corrolla','Toyota',2015, 20000,'Sedan'),
('Civic','Honda',2018, 25000,'Sedan'),
('Passo','Toyota',2012, 18000,'Hatchback'),
('Land Cruiser','Toyota',2017, 40000,'SUV'),
('Corrolla','Toyota',2011, 17000,'Sedan'),
('Vitz','Toyota',2014, 15000,'Hatchback'),
('Accord','Honda',2018, 28000,'Sedan'),
('7500','BMW',2015, 50000,'Sedan'),
('Parado','Toyota',2011, 25000,'SUV'),
('C200','Mercedez',2010, 26000,'Sedan'),
('Corrolla','Toyota',2014, 19000,'Sedan'),
('Civic','Honda',2015, 20000,'Sedan')

In the script above, we created a Showroom database with one table Car. The Car table has five attributes: CarId, Name, Make, Model, Price, and Type. Next, we added 12 dummy records in the Car table.

在上面的脚本中,我们使用一个表Car创建了一个Showroom数据库。 Car表具有五个属性:CarId,名称,品牌,型号,价格和类型。 接下来,我们在Car表中添加了12条虚拟记录。

从SQL表转换为XML (Converting into XML from SQL tables)

The simplest way to convert data from SQL tables into XML format is to use the FOR XML AUTO and FOR XML PATH clauses.

将数据从SQL表转换为XML格式的最简单方法是使用FOR XML AUTO和FOR XML PATH子句。

SQL SERVER中的FOR XML AUTO (FOR XML AUTO in SQL SERVER)

The FOR XML AUTO clause converts each column in the SQL table into an attribute in the corresponding XML document.

FOR XML AUTO子句将SQL表中的每一列转换为相应XML文档中的属性。

Execute the following script:

执行以下脚本:

USE Showroom
SELECT * FROM Car
FOR XML AUTO

In the console output you will see the following:

在控制台输出中,您将看到以下内容:

XML Auto clause output in SQL Server

Click on the link and you will see the following document in a new query window of SQL Server management studio:

单击链接,您将在SQL Server Management Studio的新查询窗口中看到以下文档:

Output of XML Auto clause in SQL Server

You can see that for each record an element Car has been created in the XML document, and for each column, an attribute with the same name has been added to each element in the XML document.

您可以看到,对于每个记录,都在XML文档中创建了一个元素Car,对于每个列,具有相同名称的属性已添加到XML文档中的每个元素。

SQL SERVER中的FOR XML PATH (FOR XML PATH in SQL SERVER)

The FOR XML AUTO class creates an XML document where each column is an attribute. On the other hand, the FOR XML PATH will create an XML document where each record is an element and each column is a nested element for a particular record. Let’s see this in action:

FOR XML AUTO类创建一个XML文档,其中每一列都是一个属性。 另一方面,FOR XML PATH将创建一个XML文档,其中每个记录是一个元素,每个列是一个特定记录的嵌套元素。 让我们来看看实际情况:

USE Showroom
SELECT * FROM Car
FOR XML PATH

A snapshot of the output is as follows:

输出快照如下:

XML Auto output in SQL Server

In the output, you will see a total of 12 elements (the screenshot shows only the first 4). You can see that each column name has been converted to an element. However, there is one problem; by default, the parent element name is “row”. We can change that using the following query:

在输出中,您将看到总共12个元素(屏幕截图仅显示前4个元素)。 您可以看到每个列名称都已转换为元素。 但是,有一个问题。 默认情况下,父元素名称为“行”。 我们可以使用以下查询来更改它:

USE Showroom
SELECT * FROM Car
FOR XML PATH ('Car')

XML path output in SQL Server when naming parent element

In the output, you can see Car as the parent element for each sub-element. However, the document is not well-formed as there is no root element in the document. To add a root element, we need to execute the following script:

在输出中,您可以将Car作为每个子元素的父元素。 但是,该文档的格式不正确,因为该文档中没有根元素。 要添加根元素,我们需要执行以下脚本:

USE Showroom
SELECT * FROM Car
FOR XML PATH ('Car'), ROOT('Cars')

In the output, you should see “Cars” as the root element as shown below:

在输出中,您应该看到“汽车”作为根元素,如下所示:

More complex XML path output in SQL Server

Now suppose you want that CarId should be the attribute of the Car element rather than an element. You can do so with the following script:

现在假设您希望CarId应该是Car元素的属性,而不是元素。 您可以使用以下脚本进行操作:

USE Showroom
SELECT  CarId as [@CarID],  
    Name  AS [CarInfo/Name],  
    Make [CarInfo/Make],  
    Model [CarInfo/Model],  
    Price,  
    Type
FROM Car 
FOR XML PATH ('Car'), ROOT('Cars')

The output looks like this:

输出看起来像这样:

Further more complex example of output when using XML path in SQL Server

You can see now that CarId has become an attribute of the Car element.

现在您可以看到CarId已成为Car元素的属性。

We can add further nesting levels to an XML document. For instance, if we want Name, Make and Model elements to be nested inside another element CarInfo we can do so with the following script:

我们可以向XML文档中添加更多的嵌套级别。 例如,如果我们希望将Name,Make和Model元素嵌套在另一个CarInfo元素内,则可以使用以下脚本进行操作:

USE Showroom
SELECT  CarId as [@CarID],  
    Name  AS [CarInfo/Name],  
    Make [CarInfo/Make],  
    Model [CarInfo/Model],  
    Price,  
    Type
FROM Car 
FOR XML PATH ('Car'), ROOT('Cars')

In the output, you will see a new element CarInfo that encloses the Name, Make and Model elements as shown below:

在输出中,您将看到一个新的CarInfo元素,其中包含Name,Make和Model元素,如下所示:

XML path output in SQL Server when adding a new XML element

Finally, if you want to convert the elements Name and Make into an attribute of element CarInfo, you can do so with the following script:

最后,如果要将元素Name和Make转换为元素CarInfo的属性,则可以使用以下脚本进行操作:

USE Showroom
SELECT  CarId as [@CarID],  
    Name  AS [CarInfo/@Name],  
    Make [CarInfo/@Make],  
    Model [CarInfo/Model],  
    Price,  
    Type
FROM Car 
FOR XML PATH ('Car'), ROOT('Cars')

The output looks like this:

输出看起来像这样:

Final example of XML path output in SQL Server to recreate full SQL table.

Save the above XML document with the name Cars.xml. In the next section, we will load this XML script into the SQL Server and will see how to create a table from the XML Document.

使用名称Cars.xml保存上述XML文档。 在下一节中,我们将把此XML脚本加载到SQL Server中,并了解如何从XML文档创建表。

For those interested in further articles on FOR XML PATH see FOR XML PATH clause in SQL Serverarticle.

对于那些对FOR XML PATH的更多文章感兴趣的人,请参阅 SQL Server文章中的 FOR XML PATH子句 。

从XML文档创建SQL表 (Creating a SQL table from an XML document)

In the previous section, we saw how to create an XML document from the SQL table. In this section, we will see how to do the reverse i.e. we will create a table in SQL using XML documents.

在上一节中,我们了解了如何从SQL表创建XML文档。 在本节中,我们将看到相反的操作,即,我们将使用XML文档在SQL中创建一个表。

The document we will use is the document that we created in the last section. One node of the document looks like this:

我们将使用的文档是我们在上一节中创建的文档。 文档的一个节点如下所示:

Example XML document to use for example of sending to SQL Server

使用XML属性创建SQL表 (Creating SQL table using XML attributes)

Let’s first see how we can create an SQL table using attributes. Suppose we want to create a table with two columns that contain the values from the Name and Make attributes from the CarInfo element. We can do so using the following script:

首先让我们看看如何使用属性创建SQL表。 假设我们要创建一个包含两列的表,其中包含来自CarInfo元素的Name和Make属性的值。 我们可以使用以下脚本进行操作:

DECLARE @cars xml
 
SELECT @cars = C
FROM OPENROWSET (BULK 'D:\Cars.xml', SINGLE_BLOB) AS Cars(C)
    
SELECT @cars
    
DECLARE @hdoc int
    
EXEC sp_xml_preparedocument @hdoc OUTPUT, @cars
SELECT *
FROM OPENXML (@hdoc, '/Cars/Car/CarInfo' , 1)
WITH(
    Name VARCHAR(100),
    Make VARCHAR(100)
    )
    
    
EXEC sp_xml_removedocument @hdoc

In the script above we declare an XML type variable @cars. The variable stores the result returned by the OPENROWSET function which retrieves XML data in binary format. Next using the SELECT @Cars statement we print the contents of the XML file. At this point in time, the XML document is loaded into the memory.

在上面的脚本中,我们声明一个XML类型变量@cars。 该变量存储OPENROWSET函数返回的结果,该函数以二进制格式检索XML数据。 接下来,使用SELECT @Cars语句,我们打印XML文件的内容。 此时,XML文档已加载到内存中。

Next, we create a handle for the XML document. To read the attributes and elements of the XML document, we need to attach the handle with the XML document. The sp_xml_preparedocument performs this task. It takes the handle and the document variable as parameters and creates an association between them.

接下来,我们为XML文档创建一个句柄。 要读取XML文档的属性和元素,我们需要将句柄附加到XML文档中。 sp_xml_prepare文档执行此任务。 它以句柄和document变量作为参数,并在它们之间创建关联。

Next, we use the OPENXML function to read the contents of the XML document. The OPENXML function takes three parameters: the handle to the XML document, the path of the node for which we want to retrieve the attributes or elements and the mode. The mode value of 1 returns the attributes only. Next, inside the WITH clause, we need to define the name and type of the attributes that you want returned. In our case the CarInfo element has two attributes Name, and Make, therefore we retrieve both.

接下来,我们使用OPENXML函数读取XML文档的内容。 OPENXML函数采用三个参数:XML文档的句柄,我们要为其检索属性或元素的节点的路径以及模式。 模式值1仅返回属性。 接下来,在WITH子句中,我们需要定义要返回的属性的名称和类型。 在我们的例子中,CarInfo元素具有两个属性Name和Make,因此我们同时检索了这两个属性。

As a final step, we execute the sp_xml_removedocument stored procedure to remove the XML document from the memory. In the output you will see values from the Name and Make attributes of the CarInfo element as shown below:

最后一步,我们执行sp_xml_removedocument存储过程以从内存中删除XML文档。 在输出中,您将看到CarInfo元素的Name和Make属性的值,如下所示:

SQL server table output of XML data

使用XML元素创建SQL表 (Creating a SQL table using XML elements)

To create a SQL table using XML elements, all you have to do is to change the mode value of the OPENXML function to 2 and change the name of the attributes to the name of the element you want to retrieve.

要使用XML元素创建SQL表,您要做的就是将OPENXML函数的mode值更改为2,并将属性名称更改为要检索的元素名称。

Suppose we want to retrieve the values for the nested CarInfo, Price and Type elements of the parent Car element, we can use the following script:

假设我们要检索父Car元素的嵌套CarInfo,Price和Type元素的值,我们可以使用以下脚本:

DECLARE @cars xml
 
SELECT @cars = C
FROM OPENROWSET (BULK 'D:\Cars.xml', SINGLE_BLOB) AS Cars(C)
    
SELECT @cars
    
DECLARE @hdoc int
    
EXEC sp_xml_preparedocument @hdoc OUTPUT, @cars
SELECT *
FROM OPENXML (@hdoc, '/Cars/Car' , 2)
WITH(
    CarInfo INT,
    Price INT,
    Type VARCHAR(100)
    )
    
    
EXEC sp_xml_removedocument @hdoc

Output of the script above looks like this:

上面脚本的输出如下所示:

SQL table output for more complicated XML to SQL transfer

结论 (Conclusion)

XML is one of the most popular data formats for information exchange. In this article, we saw how we can create a document using XML from a SQL table. We also saw how to import into a table in SQL from an XML document.

XML是最流行的信息交换数据格式之一。 在本文中,我们了解了如何使用SQL表中的XML创建文档。 我们还看到了如何从XML文档导入到SQL表中。

翻译自: https://www.sqlshack.com/working-with-xml-data-in-sql-server/

culuo4781
关注 关注
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
机器学习1:OpenCV4.5.5加载xml进行车辆识别
meng_nan666的博客
07-17 2049
网上大部分机器学习的例程都是OpenCV早期版本状态下的,新安装了OpenCV4.5.5后这些例程都无法编译使用了,因此参考OpenCV自带例程进行了例程改写,给出了在OpenCV4.5.5下的机器学习xml模型加载及目标识别显示的例程。...
opencv车辆识别 训练模型文件 cars.xml
06-06
opencv 车辆识别 训练模型文件 cars.xml
7、XML数据类型的高级应用
路在何方
10-08 1593
在本章前面的各小节,主要围绕在SQL Server 2005 如何对XML数据本身操作的方法进行了讲解。这一节的内容则是围绕如何将T-SQL查询的结果转换成XML形式,以及如何将对XML数据的查询转换成T-SQL结果集的形式。 11.7.1  使用 OPENXML
SQL Server XML
u010653281的博客
08-03 377
SQL SERVER XML USAGE
使SQLServer数据支持XML
02-27
北京火龙果软件工程技术心学习如何用SQLServerXML特征为你的数据库提供新的功能。如果你在IT业工作,那么你很可能听说过...在本月的专栏,我将讲述SQLServerXML的内置的支持,并讲述通过发布SQLXML而增加的一
SQL Server解析XML数据的方法详解
09-10
主要介绍了SQL Server解析XML数据的方法,结合实例形式详细分析了SQL Server针对xml数据的读取,遍历,删除,查找等常用操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下
SQL Server 2005使用XML数据.pdf
09-19
SQL Server 2005使用XML数据.pdf
基于OpenCV测车距项目
weixin_64437665的博客
04-27 635
这是一个基于OpenCV的Python代码示例,用于估计车辆之间的距离。此代码使用摄像头捕获视频并检测车辆,并通过三角测量来估计车辆之间的距离。注意:cars.xml是一个Haar级联分类器文件,用于检测车辆。在运行代码之前,请确保将IMAGE_PATH替换为你要计算距离的图像文件的路径。KNOWN_WIDTH = 1.8 # 已知车辆宽度,单位:米。首先,请确保安装了opencv-python和其他必要的库。FOCAL_LENGTH = 700 # 焦距,单位:像素。# 从图片读取数据
Sql Server STUFF与FOR XML PATH
沧鹫小hai的博客
05-10 1638
要求按type分组查询后,把相同type的,name列值合并,达到如下效果: 解析如下: 一、FOR xml path      FOR XML PATH 有的人可能知道有的人可能不知道,其实它就是将查询结果集以XML形式展现,有了它我们可以简化我们的查询语句实现一些以前可能需要借助函数活存储过程来完成的工作。那么以一个实例为主. 假设有张查询表如下 sql 一:select t
SQLServer XML数据的五种基本操作
GuoGuoABC
05-31 2744
一、前言 从 SQL Server 2005 开始,就增加了 xml 字段类型,也就是说可以直接把 xml 内容存储在该字段,并且 SQL Server 会把它当作 xml 来对待,而不是当作 varchar 来对待。 随着SQL ServerXML字段的支持,相应的,T-SQL语句也提供了大量对XML操作的功能来配合SQL ServerXML字段的使用。本文主要说明如何使用SQL语句对XML进行操作。 二、定义XML字段 在进行数据库的设计,我们可以在表设计器,很方...
SQL Server解析XML数据
vvull的博客
03-06 488
因为IT说SQL Server兼容级别高影响性能,所以改用XMLOPENXML (SQL Server)OPENXML (Transact-SQL)
OpenCV学习笔记(二十一)——车辆识别和跟踪
热门推荐
行歌
05-16 1万+
     今天在GitHub上看到一个对车辆训练好的模型,即xml文件,于是拿来测试了一个效果。我用这个xml文件对视频的每一帧画面进行简单的车辆识别定位,演示代码如下:import cv2 import numpy as np camera = cv2.VideoCapture ("video.avi") camera.open("video.avi") car_cascade = cv2....
SQL Server XML数据的五种基本操作
灰太狼的博客
07-21 1万+
1.xml.exist    输入为XQuery表达式,返回0,1或是Null。0表示不存在,1表示存在,Null表示输入为空 2.xml.value    输入为XQuery表达式,返回一个SQL Server标量值 3.xml.query    输入为XQuery表达式,返回一个SQL Server XML类型流 4.xml.nodes    输入为XQuery表达式,返回一个XML格式文档的
java opencv 之车辆识别
qq_34565436的博客
04-08 4464
上篇写了人脸识别,因为人脸识别的训练模型 haarcascade_frontalface_alt.xml 之类的官方已经训练好了可以直接用,但是我们要识别车辆或者其它物体就得训练模型,好在废了一点力 找到了一位大神训练好的模型 核心代码 几乎和人脸识别的差不多 static CascadeClassifier carDetector; static { try { NativeLoader.loader(); ...
sql serverxml进行操作
weixin_30576859的博客
12-08 111
一、前言 SQL Server 2005 引入了一种称为 XML 的本机数据类型。用户可以创建这样的表,它在关系列之外还有一个或多个 XML 类型的列;此外,还允许带有变量和参数。为了更好地支持 XML 模型特征(例如文档顺序和递归结构),XML 值以内部格式存储为大型二进制对象 (BLOB)。 用户将一个XML数据存入数据库的时候,可以使用这个XML的字符串,SQL Server会自动的将这...
SQL ServerXML数据类型简介
culuo4781的博客
07-25 2788
The XML data type is a very common data type that is used to store unstructured or heterogeneous data in SQL Server. In this article, we will discuss the use of the XML data type along with...
XML格式怎么在sqlserver数据解析转换
最新发布
05-26
SQL Server,可以使用内置的XML函数和方法来解析和转换XML格式的数据。以下是一些常用的XML函数和方法: 1. CONVERT函数:可以将XML类型的数据转换为VARCHAR类型的数据。 2. CAST函数:可以将XML类型的数据...

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
写文章

热门文章

  • SQL Server函数将字符串转换为日期 37236
  • sql添加列_SQL添加列操作 36609
  • sql中的while循环_SQL While循环:了解SQL Server中的While循环 30934
  • insert sql语句_SQL Insert语句概述 26931
  • power bi排序_如何在Power BI中按时间顺序对月份进行排序 23242

您愿意向朋友推荐“博客详情页”吗?

  • 强烈不推荐
  • 不推荐
  • 一般般
  • 推荐
  • 强烈推荐
提交

最新文章

  • sql:命名管道管道程序_学习SQL:命名约定
  • 使用Diskspd测试SQL Server存储子系统
  • mysql分页是物理分页_学习MySQL:什么是分页
2020年1809篇

目录

目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值

聚圣源猎头公司起名小米盒子软件家居用品起名黑与白陶瓷日杂百货小店起名大全异地汇款手续费惊弓之鸟的意思真假威龙周易起名哪个动画片起名ktv软件广东卫视在线直播芯片公司起名宝宝五行缺木起名男蔡微澜寓意好的成语可起名称天蝎女和金牛男兄弟建群起什么名字给男孩起个有诗意好名字大全狐假虎威文言文漳州虹雨浏览器兄弟懂的拿走不谢2021游戏签名鞍山起名国势txt政通人和宝易互通支付平台电缆厂起名大全公安部副部长电信套餐淀粉肠小王子日销售额涨超10倍罗斯否认插足凯特王妃婚姻让美丽中国“从细节出发”清明节放假3天调休1天男孩疑遭霸凌 家长讨说法被踢出群国产伟哥去年销售近13亿网友建议重庆地铁不准乘客携带菜筐雅江山火三名扑火人员牺牲系谣言代拍被何赛飞拿着魔杖追着打月嫂回应掌掴婴儿是在赶虫子山西高速一大巴发生事故 已致13死高中生被打伤下体休学 邯郸通报李梦为奥运任务婉拒WNBA邀请19岁小伙救下5人后溺亡 多方发声王树国3次鞠躬告别西交大师生单亲妈妈陷入热恋 14岁儿子报警315晚会后胖东来又人满为患了倪萍分享减重40斤方法王楚钦登顶三项第一今日春分两大学生合买彩票中奖一人不认账张家界的山上“长”满了韩国人?周杰伦一审败诉网易房客欠租失踪 房东直发愁男子持台球杆殴打2名女店员被抓男子被猫抓伤后确诊“猫抓病”“重生之我在北大当嫡校长”槽头肉企业被曝光前生意红火男孩8年未见母亲被告知被遗忘恒大被罚41.75亿到底怎么缴网友洛杉矶偶遇贾玲杨倩无缘巴黎奥运张立群任西安交通大学校长黑马情侣提车了西双版纳热带植物园回应蜉蝣大爆发妈妈回应孩子在校撞护栏坠楼考生莫言也上北大硕士复试名单了韩国首次吊销离岗医生执照奥巴马现身唐宁街 黑色着装引猜测沈阳一轿车冲入人行道致3死2伤阿根廷将发行1万与2万面值的纸币外国人感慨凌晨的中国很安全男子被流浪猫绊倒 投喂者赔24万手机成瘾是影响睡眠质量重要因素春分“立蛋”成功率更高?胖东来员工每周单休无小长假“开封王婆”爆火:促成四五十对专家建议不必谈骨泥色变浙江一高校内汽车冲撞行人 多人受伤许家印被限制高消费

聚圣源 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化