【问题标题】:How do I suppress empty namespaces with FOR XML in Sql Server如何在 Sql Server 中使用 FOR XML 抑制空命名空间
【发布时间】:2010-02-26 18:48:27
【问题描述】:

我们在 SQL Server 2005/2008 中遇到了一个奇怪的问题,它使用带有 xml 片段和命名空间的 FOR XML。这是有问题的查询。

WITH XMLNAMESPACES ( 
DEFAULT 'http://tempuri.org/newincomingxml.xsd',
'http://tempuri.org/newincomingxml.xsd' as [xsi],
'http://tempuri.org/newincomingxml.xsd' as [a]
) 
SELECT 
 [@a:Source], [AddressCount], [ConsumerCount], [EmailCount], [PermissionCount]
, (
  SELECT 
   [Consumer]
  FROM tbcExportBRC_Current xmlmaster
  FOR XML PATH(''), ROOT('Consumers'), TYPE
 )
FROM tbcExportBRCBatch_Current xmlroot
FOR XML PATH('Datafeed'), TYPE

[Customer] 字段是一个 xml 片段。当我运行它时,我得到了。

<Datafeed xmlns:a="http://tempuri.org/newincomingxml.xsd" xmlns:xsi="http://tempuri.org/newincomingxml.xsd" xmlns="http://tempuri.org/newincomingxml.xsd" a:Source="DSD">
  <AddressCount>0</AddressCount>
  <ConsumerCount>0</ConsumerCount>
  <EmailCount>0</EmailCount>
  <PermissionCount>0</PermissionCount>
  <Consumers xmlns:a="http://tempuri.org/newincomingxml.xsd" xmlns:xsi="http://tempuri.org/newincomingxml.xsd" xmlns="http://tempuri.org/newincomingxml.xsd">
    <Consumer>
      <ConsumerType xmlns="">Individual</ConsumerType>
      <FirstName xmlns="">STEVE</FirstName>
      <LastName xmlns="">SMITH</LastName>
    </Consumer>
  </Consumers>
</Datafeed>

如果您注意到标签的子标签中有 xmlns=""。如果我们直接在表格中查看片段,它看起来像这样。

      <ConsumerType>Individual</ConsumerType>
      <FirstName>STEVE</FirstName>
      <LastName>SMITH</LastName>

我可以删除默认命名空间

DEFAULT 'http://tempuri.org/newincomingxml.xsd',

它删除了 xmlns="" 但我们需要将其保留在文件中。有什么想法吗?

【问题讨论】:

    标签: sql-server xml namespaces for-xml


    【解决方案1】:

    结果是正确的。在表中,您有没有命名空间的元素,因此当您将它们添加到消费者元素下默认命名空间为 xmlns="http://tempuri.org/newincomingxml.xsd" 时,元素来自表必须将默认命名空间覆盖回“”。

    这正是您应该看到的。没有 xmlns="" 意味着 ConsumerType/FirstName/LastName 元素位于命名空间“http://tempuri.org/newincomingxml.xsd”中,这是错误的。

    您可能想要将 ConsumerType/FirstName/LastName 元素移动到“http://tempuri.org/newincomingxml.xsd”命名空间中,以匹配父 Consumer 元素的命名空间。

    【讨论】:

    • 你说的很有道理。我编辑了我的原始帖子,因为我意识到我在消费者列中的片段是不正确的。如何指定它也属于哪个命名空间而不在每一行上放置 xmlns="tempuri.org/newincomingxml.xsd"?
    • &lt;Consumers ... xmlns:c="http://tempuri.org/newincomingxml.xsd" ...&gt;&lt;c:Consumer&gt;...&lt;/c:Consumer&gt;...&lt;/Consumers&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多