3

我正在尝试使用FOR XMLSQL 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>

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

4

1 回答 1

4

你不是一个人。

http://connect.microsoft.com/SQLServer/feedback/details/265956/suppress-namespace-attributes-in-nested-select-for-xml-statements

我建议支持这一改进。

上面的连接站点列出了一种解决方法:

http://www.olcot.co.uk/sql-blogs/suppressing-namespace-attributes-in-nested-select-statements-when-using-for-xml-workaround

附加/编辑:

我在上面发布的第二个链接现在已经死了。

这是一个不同的链接:

http://www.sqlservercentral.com/blogs/rocks/2012/08/28/suppressing-namespace-attributes-in-nested-select-statements-when-using-for-xml-workaround/

于 2013-05-21T14:20:14.273 回答