关于将sql server的xml列生成xml文件的方法

找了一圈没找到相关文章,摸索了一下总算是搞出来了。下面追忆一下折腾的过程。

关于xml解析的方法参见上一篇文章

sql server解析xml文件并生成多个表

进入正题:

创建包含xml列的表

create table即可,xml为sql server支持存储的格式之一

CREATE TABLE bookxml(
	year int,
	title VARCHAR(100),
	auORed XML,
	publisher VARCHAR(50),
	price VARCHAR(50));

(记得使用自己的数据库)

插入使用insert into语句即可


根据表格生成xml文件

使用for xml path可以直接生成,但是路上会遇到一些问题。下面贴源码:

select year as '@year',title,auORed,publisher,price
from bookxml B
FOR XML PATH('book'),ROOT('bib')

但是查询出来会把auORed作为XML列的标签(XML列的数据是作为一个整体存储下来的)

<bib>
  <book year="2000">
    <title>Data on the Web</title>
    <auORed>
      <author>
        <last>Abiteboul</last>
        <first>Serge</first>
      </author>
      <author>
        <last>Buneman</last>
        <first>Peter</first>
      </author>
      <author>
        <last>Suciu</last>
        <first>Dan</first>
      </author>
    </auORed>
    <publisher>Morgan Kaufmann Publishers</publisher>
    <price>39.95</price>
  </book>
</bib>

使用 auORed as 'authors' 可以更改标签名,但是如果我们不想要标签的话。。。

这时候就需要使用query

解决方法
select year as '@year',title,auORed.query('*'),publisher,price
from bookxml B
FOR XML PATH('book'),ROOT('bib')

将auORed修改为auORed.query('*'),这里使用的*会直接查询auOEed的所有子节点,也就跳过了auORed标签。来看看效果如何吧:

<bib>
  <book year="2000">
    <title>Data on the Web</title>
    <author>
      <last>Abiteboul</last>
      <first>Serge</first>
    </author>
    <author>
      <last>Buneman</last>
      <first>Peter</first>
    </author>
    <author>
      <last>Suciu</last>
      <first>Dan</first>
    </author>
    <publisher>Morgan Kaufmann Publishers</publisher>
    <price>39.95</price>
  </book>
</bib>
OK。打完收工。

猜你喜欢

转载自blog.csdn.net/l1070628834/article/details/80373939
今日推荐