如何将WITH XMLNAMESPACES子句与相关查询一起使用?

时间:2013-05-21 13:58:23

标签: sql-server for-xml

我正在尝试使用SQL Server的FOR XML功能生成一些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>

是否可以调整查询以使命名空间正确,或者我是否必须将其加载到“其他内容”以删除冗余的命名空间声明?