I'm trying to export some data from a database in a particular XML format specified by the customer. 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.
The customer has requested data on each product like so:
<product id="1234567890123"> <activeState partNumber="A1234567890" shipmentDate="20110518" /> </product>
My existing SQL is:
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. My first ambition was to simply express the id as an attribute of product rather than as a child element. 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...
Any suggestions?
SQL Server provides the XQuery feature to querying XML data type or querying with the XML column with the XPATH. Using XQuery, users can Insert, Update and Delete with the XML nodes and node values in an XML column.
Attributes are part of XML elements. An element can have multiple unique attributes. Attribute gives more information about XML elements. To be more precise, they define properties of elements.
In SQL Server, you usually store XML data in a column configured with the xml data type. The data type supports several methods that let you query and modify individual elements, attributes, and their values directly within the XML instance, rather than having to work with that instance as a whole.
SQL Server lets you retrieve data as XML by supporting the FOR XML clause, which can be included as part of your query. You can use the FOR XML clause in the main (outer) query as well as in subqueries. The clause supports numerous options that let you define the format of the XML data.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With