用于xml显式处理命名空间

时间:2016-07-21 23:49:44

标签: sql xml sql-server-2012 xml-namespaces

我正在尝试查询explicit xml。为此,我必须使用namespace。这是一个简化版本:

SELECT 1                   as Tag,  
       NULL                as Parent,  
       i.SSN               as [SSN!1]
FROM   IRS_Table  as i
for xml explicit

但我希望xml看起来像这样:

<irs:SSN>999-99-9999</irs:SSN>

以下是开头标记中的命名空间声明:

xmlns:irs="urn:us:gov:treasury:irs:common"

如何修改脚本以便在输出命名空间中查看?

修改

    <?xml version="1.0" encoding="utf-8"?>
    <n1:Form109495CTransmittalUpstream xmlns:irs="urn:us:gov:treasury:irs:common">
        <irs:SSN>999-99-9999</irs:SSN>
    </n1:Form109495CTransmittalUpstream>

1 个答案:

答案 0 :(得分:1)

您可以使用以下查询将名称空间包含在for xml explicit输出中。

SELECT 1                   as Tag,  
       NULL                as Parent,  
       i.SSN               as [irs:SSN!1],
       'urn:us:gov:treasury:irs:common' as [irs:SSN!1!xmlns:irs] --namespace is here
FROM   IRS_Table as i
for xml  explicit

更新

使用for xml path构建可能更容易。

;with xmlnamespaces('urn:us:gov:treasury:irs:common' as irs,
                    'blahblah' as n1,
                     default 'blahblah:blah' )
SELECT  
       null as [n1:Form109495CTransmittalUpstream], 
       ssn  as [n1:Form109495CTransmittalUpstream/irs:SSN]
FROM   IRS_Table as i
for xml path(''), elements, root