我正在尝试使用FOR XML
SQL Server 的特性来生成一些带有特定命名空间的 XML。
我的目标 XML 应该类似于:
<ns1:CustomerInvoices xmlns:ns1="urn:example.com:Invoice:01.00">
<CustomerInvoice>
<Header>
<OrderDate>2001-11-13T00:00:00</OrderDate>
<SalesOrderNumber>SO44643</SalesOrderNumber>
</Header>
<Lines>
<LineTotal>3578.270000</LineTotal>
<UnitPrice>3578.2700</UnitPrice>
<OrderQty>1</OrderQty>
</Lines>
</CustomerInvoice>
<CustomerInvoice>...(abbreviated)...</CustomerInvoice>
</ns1:CustomerInvoices>
我遇到的问题是,当我使用该WITH XMLNAMESPACES
子句时,命名空间声明是否出现在许多子节点上,这个 XML 的第三方消费者会“不希望得到”,即我正在做类似的事情:
Use AdventureWorks2008
;WITH XMLNAMESPACES ('urn:example.com:Invoice:01.00' as ns1)
SELECT (SELECT hdr.OrderDate,
hdr.SalesOrderNumber
FOR XML PATH (''), TYPE) AS Header,
(SELECT line.LineTotal,
line.UnitPrice,
line.OrderQty
FROM Sales.SalesOrderDetail AS line
WHERE line.SalesOrderID = hdr.SalesOrderID
FOR XML PATH (''), TYPE) AS Lines
FROM Sales.SalesOrderHeader AS hdr
WHERE hdr.ModifiedDate = '2001-11-20'
FOR XML PATH('CustomerInvoice'), ROOT('ns1:CustomerInvoices')
这使:
<ns1:CustomerInvoices xmlns:ns1="urn:example.com:Invoice:01.00">
<CustomerInvoice>
<Header>
<OrderDate xmlns:ns1="urn:example.com:Invoice:01.00">2001-11-13T00:00:00</OrderDate>
<SalesOrderNumber xmlns:ns1="urn:example.com:Invoice:01.00">SO44643</SalesOrderNumber>
</Header>
<Lines>
<LineTotal xmlns:ns1="urn:example.com:Invoice:01.00">3578.270000</LineTotal>
<UnitPrice xmlns:ns1="urn:example.com:Invoice:01.00">3578.2700</UnitPrice>
<OrderQty xmlns:ns1="urn:example.com:Invoice:01.00">1</OrderQty>
</Lines>
</CustomerInvoice>
<CustomerInvoice>...(abbreviated)...</CustomerInvoice>
</ns1:CustomerInvoices>
是否可以调整查询以使命名空间正确,或者我是否必须将其加载到“其他”中以删除多余的命名空间声明?