将XML从一种格式转换为另一种格式

时间:2016-10-20 10:38:33

标签: sql-server xml tsql xpath xquery

我有以下xml数据存储在表中。

我有的XML结构

<Response>
    <Question ID="1">
        <Value ID="1">I want a completely natural childbirth - no medical interventions for me</Value>
        <Value ID="2">no medical interventions for me</Value>
    </Question>
</Response>

我需要将此XML转换为稍微不同的格式,如下所示。

我需要的XML结构

<Response>
    <Question ID="1">
        <SelectedChoices>
            <Choice>
                <ID>1</ID>
            </Choice>
            <Choice>
                <ID>2</ID>
            </Choice>
        </SelectedChoices>
    </Question>
</Response>

此处“Value”更改为“Choice”,“Value”元素的“ID”属性更改为元素。

我知道这可以在other ways中完成,就像使用XSLT一样。但是如果可以用SQL本身完成它将会更有帮助。

有人可以帮助我使用SQL转换它吗?

1 个答案:

答案 0 :(得分:2)

Use this variable to test the statements

DECLARE @xml XML=
N'<Response>
    <Question ID="1">
        <Value ID="1">I want a completely natural childbirth - no medical interventions for me</Value>
        <Value ID="2">no medical interventions for me</Value>
    </Question>
</Response>';

This can be done with FLWOR-XQuery:

The query will re-build the XML out of itself... Very similar to XSLT...

SELECT @xml.query(
N'
<Response>
{
for $q in /Response/Question
    return 
    <Question ID="{$q/@ID}">
    <SelectedChoices>
    {
    for $v in $q/Value
        return <Choice><ID>{string($v/@ID)}</ID></Choice>
    }
    </SelectedChoices>
    </Question>
}
</Response>
'
);

Another approach: Shredding and re-build

You'd reach the same with this, but I'd prefere the first...

WITH Shredded AS
(
    SELECT q.value('@ID','int') AS qID
          ,v.value('@ID','int') AS vID
    FROM @xml.nodes('/Response/Question') AS A(q)
    OUTER APPLY q.nodes('Value') AS B(v)
)
SELECT t1.qID AS [@ID]
      ,(
        SELECT t2.vID AS ID
        FROM Shredded AS t2
        WHERE t1.qID=t2.qID
        FOR XML PATH('Choice'),ROOT('SelectedChoices'),TYPE
       ) AS [node()]
FROM Shredded AS t1
GROUP BY t1.qID
FOR XML PATH('Question'),ROOT('Response')