简体   繁体   English

SQL FOR XML - 将数据输出为元素或属性

[英]SQL FOR XML - Outputting data as Elements or as Attributes

I'm trying to export some data from a database in a particular XML format specified by the customer. 我正在尝试以客户指定的特定XML格式从数据库导出一些数据。 The XML I produce will be manipulated (presumably by XSLT) by a 3rd party to produce the final output, but I want to formal my XML as close as I can to that format. 我生成的XML将由第三方操纵(可能是由XSLT)来生成最终输出,但我想尽可能地将我的XML格式化为该格式。

The customer has requested data on each product like so: 客户要求每个产品的数据如下:

<product id="1234567890123">
    <activeState partNumber="A1234567890" shipmentDate="20110518" />
</product>

My existing SQL is: 我现有的SQL是:

SELECT SerialNo as id, 
    PartNo as partNumber,
    CONVERT(VARCHAR(8), GETDATE(), 112) AS shipmentDate, 
FROM Products
WHERE SerialNo = @SerialNo
FOR XML PATH ('product'), TYPE)

...which renders: ...呈现:

<product>
  <id>100000000458</id>
  <partNumber>10004905892</partNumber>
  <shipmentDate>20120312</shipmentDate>
</product>

I expect that it is easy enough to manipulate this data in XSLT, but purely as an intellectual exercise, I'd like to see how far I could in SQL. 我希望在XSLT中操作这些数据很容易,但纯粹作为一种智力练习,我想看看我能在SQL中走多远。 My first ambition was to simply express the id as an attribute of product rather than as a child element. 我的第一个目标是简单地将id表示为产品的属性而不是作为子元素。 The rendering of the activeState element I was going to leave to the XSLT, but clearly, if I can help them on their way, why not do so... 我将把这个activeState元素的渲染留给XSLT,但显然,如果我可以帮助他们的话,为什么不这样做呢......

Any suggestions? 有什么建议么?

Use @ to create attributes. 使用@创建属性。

select SerialNo as "@id",
       PartNo as "activeState/@partNumber",
       convert(varchar(8), getdate(), 112) as "activeState/@shipmentDate"
from Products
where SerialNo = @SerialNo
for xml path('product')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM