【问题标题】:SQL Server Xml Namespace Querying ProblemSQL Server Xml 命名空间查询问题
【发布时间】:2010-11-02 20:41:47
【问题描述】:

我在 xml 变量 @ResultData 中有以下内容

<EntityKey_x005B__x005D_>
  <EntityKey>
    <KeyData xmlns="http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey">
      <KeyField>
        <Field>JournalNum</Field>
        <Value>LJRN000071</Value>
      </KeyField>
    </KeyData>
  </EntityKey>
  <EntityKey>
    <KeyData xmlns="http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey">
      <KeyField>
        <Field>JournalNum</Field>
        <Value>LJRN000072</Value>
      </KeyField>
    </KeyData>
  </EntityKey>
  <EntityKey>
    <KeyData xmlns="http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey">
      <KeyField>
        <Field>JournalNum</Field>
        <Value>LJRN000073</Value>
      </KeyField>
    </KeyData>
  </EntityKey>
  <EntityKey>
    <KeyData xmlns="http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey">
      <KeyField>
        <Field>JournalNum</Field>
        <Value>LJRN000074</Value>
      </KeyField>
    </KeyData>
  </EntityKey>
</EntityKey_x005B__x005D_>

但由于节点上的xmlns=...,我似乎无法从中选择 JournalNum 值。在 .Net 中,我可以执行 "{http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey}KeyData" 之类的操作来检索它,但我在 SQL 中遇到语法错误。

我只想按文档顺序将 Value 节点列表放入临时表中,但这也不起作用....

SELECT  IDENTITY(int,1,1) as 'ID',
    c.query('(KeyData/KeyField/Value)[1]') as 'JournalNum'
INTO    #tmpBatches
FROM    @ResultData.nodes('//EntityKey') t(c)

想法?建议?解决方案?

【问题讨论】:

    标签: xml sql-server-2008 namespaces xpath


    【解决方案1】:

    知道了……当然,问完就知道了

        ;WITH XMLNAMESPACES (N'http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey' as DYN)
        SELECT  IDENTITY(int,1,1)   
                    as 'ID',
                c.value('(DYN:KeyData/DYN:KeyField/DYN:Value)[1]', 'VARCHAR(40)')
                    as 'JournalNum'
        INTO    #tmpBatches
        FROM    @ResultData.nodes('//EntityKey') t(c)
    

    【讨论】:

    • 非常感谢!!我终于在我的 xpath 查询中摆脱了这些讨厌的命名空间。
    【解决方案2】:

    由于您只有一个命名空间,您可以使用 DEFAULT 来避免必须在任何地方添加前缀:

     ;WITH XMLNAMESPACES (DEFAULT N'http://schemas.microsoft.com/dynamics/2006/02/documents/EntityKey') 
            SELECT   IDENTITY(int,1,1)                                                
            as 'ID', c.value('(<strike>DYN:</strike>KeyData/DYN:KeyField/DYN:Value)[1]', 'VARCHAR(40)')
            as 'JournalNum'
                INTO #tmpBatches
            FROM @ResultData.nodes('//EntityKey') t(c)
    

    此外,我偶然发现了一些关于如何忽略所有命名空间的注释,因为当有多个命名空间并且您知道不会发生冲突时。 Someone's blog.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2014-05-14
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多