[英]How to create XML nodes with attributes from Table
I have following example table 我有以下示例表
Code here 在这里编码
CREATE TABLE XMLData
(
NodeName NVARCHAR(255),
AttributA NVARCHAR(255),
AttributB NVARCHAR(255),
AttributC NVARCHAR(255),
)
INSERT INTO XMLData VALUES
('RowA','','abcd','efgh'),
('RowB','wxyz',NULL,NULL),
('RowC',NULL,'qwer','tyui'),
('RowD','stuv','erty','fghj')
SELECT * FROM dbo.XMLData
How can I get following XML ? 如何获得XML?
<NodeA>
<NodeB />
<NodeC AttributeX="">
<RowA AttributeA="" AttributeB="abcd" AttributeC="efgh" />
<RowB AttributeA="wxyz" />
<RowC AttributeB="qwer" AttributeC="tyui" />
<RowD AttributeA="stuv" AttributeB="erty" AttributeC="fghj" />
</NodeC>
</NodeA>
I am beginner with XML, but I tried to play with something like this 我是XML的初学者,但我尝试使用这种方法
SELECT
(
SELECT
(
SELECT '' AS '@AttributeX' FOR XML PATH('NodeC'),TYPE
-- How to get table rows here ?
)
FOR XML PATH('NodeB'),TYPE -- Here it creates additional end NodeB tag
)
FOR XML PATH('NodeA'),TYPE
This is - almost - what you wanted. 这几乎是您想要的。 As told in my comment you will not be able to create your Element's names (
<RowA>
etc.) dynamically. 如我的评论所述,您将无法动态创建元素的名称(
<RowA>
等)。 For this you'd have to use dynamic SQL and I assume this is not what you want actually... 为此,您必须使用动态SQL,并且我认为这实际上不是您想要的...
Here's my suggestion: 这是我的建议:
SELECT '' AS [NodeB]
,'' AS [NodeC/@AttributeX]
,(
SELECT x.NodeName AS [@NodeName]
,x.AttributA AS [@AttributeA]
,x.AttributB AS [@AttributeB]
,x.AttributC AS [@AttributeC]
FROM XMLData AS x
FOR XML PATH('Row'),TYPE
) AS NodeC
FOR XML PATH(''),ROOT('NodeA')
The result 结果
<NodeA>
<NodeB></NodeB>
<NodeC AttributeX="">
<Row NodeName="RowA" AttributeA="" AttributeB="abcd" AttributeC="efgh" />
<Row NodeName="RowB" AttributeA="wxyz" />
<Row NodeName="RowC" AttributeB="qwer" AttributeC="tyui" />
<Row NodeName="RowD" AttributeA="stuv" AttributeB="erty" AttributeC="fghj" />
</NodeC>
</NodeA>
This was an XSLT to get "dynamic" element names out of the XML above 这是一个XSLT,用于从上面的XML中获取“动态”元素名称
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[@NodeName]">
<xsl:element name="{@NodeName}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@NodeName" />
</xsl:stylesheet>
And this was the result Test it here 这就是结果在这里测试
<NodeA>
<NodeB/>
<NodeC AttributeX="">
<RowA AttributeA="" AttributeB="abcd" AttributeC="efgh"/>
<RowB AttributeA="wxyz"/>
<RowC AttributeB="qwer" AttributeC="tyui"/>
<RowD AttributeA="stuv" AttributeB="erty" AttributeC="fghj"/>
</NodeC>
</NodeA>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.