在sql中查询XML值

时间:2014-11-25 11:28:36

标签: sql-server xml

我需要从SQL Server 2008中的XML中获取一些信息,但我甚至无法从中获取基本属性。我试过的所有样品都失败了。表名为Item,xml列名为Data

简化的xml如下所示:

<AnchoredXml xmlns="urn:schema:Microsoft.Rtc.Management.ScopeFramework.2008" SchemaWriteVersion="2">
  <Key ScopeClass="Global">
    <SchemaId Namespace="urn:schema:Microsoft.Rtc.Management.Deploy.Topology.2008" ElementName="Topology" />
    <AuthorityId Class="Host" InstanceId="00000000-0000-0000-0000-000000000000" />
  </Key>
  <Dictionary Count="1">
    <Item>
      <Key />
      <Value Signature="a3502dd0-8c16-4023-9eea-30ea1c7a3a2b">
        <Topology xmlns="urn:schema:Microsoft.Rtc.Management.Deploy.Topology.2008">
          <Services>
            <Service RoleVersion="1" ServiceVersion="6" Type="Microsoft.Rtc.Management.Deploy.Internal.ServiceRoles.FileStoreService">
              <ServiceId SiteId="1" RoleName="FileStore" Instance="1" />
              <DependsOn />
              <InstalledOn>
                <ClusterId SiteId="1" Number="1" />
              </InstalledOn>
              <Ports xmlns="urn:schema:Microsoft.Rtc.Management.Deploy.ServiceRoles.2008" />
              <FileStoreService xmlns="urn:schema:Microsoft.Rtc.Management.Deploy.ServiceRoles.2008" ShareName="lyncShare" />
            </Service>
          </Services>
        </Topology>
      </Value>
    </Item>
  </Dictionary>
</AnchoredXml>

我需要读取AnchoredXml / Key / SchemaId / @ NameSpace中的信息以选择正确的xml(还有更多行)。上面的示例xml是正确的。之后我需要找到合适的服务

Type="Microsoft.Rtc.Management.Deploy.Internal.ServiceRoles.FileStoreService"

我需要的FileStoreService / @ ShareName在哪里。

我尝试打开Namespace attributte作为开始,但没有示例代码正常工作。 几次尝试:

SELECT c.p.value('(@Namespace)[1]', 'varchar(50)') as 'Nmspace'
FROM Item
CROSS APPLY Data.nodes('/AnchoredXml/Key/SchemaId') c(p)

返回空结果集

SELECT Data.value('(/AnchoredXml/Key/SchemaId/@Namespace)[1]', 'varchar(50)') 
FROM Item

为所有行返回NULL

SELECT
It.Data.exist('/AnchoredXml/Key/SchemaId[@Namespace="Microsoft.Rtc.Management.Deploy.Topology.2008"]')
FROM [xds].[dbo].[Item] AS It

为所有行返回0,也没有引号(“”)

至少获得属性测试的工作示例代码可能就足够了,我会弄清楚剩下的。 你能帮我查一下我的查询中的错误,或者找出其他一些问题吗? 感谢

1 个答案:

答案 0 :(得分:1)

您忽略了XML文档中的所有 XML命名空间!你需要注意那些并尊重他们!

有以下XML命名空间:

  • 根节点<AnchoredXml>
    (XML名称空间:urn:schema:Microsoft.Rtc.Management.ScopeFramework.2008
  • 子节点<Topology>
    (XML ns:urn:schema:Microsoft.Rtc.Management.Deploy.Topology.2008
  • 子节点<FileStoreService>
    (XML ns:urn:schema:Microsoft.Rtc.Management.Deploy.ServiceRoles.2008

试试这个:

-- respect the XML namespaces!!
;WITH XMLNAMESPACES(DEFAULT 'urn:schema:Microsoft.Rtc.Management.ScopeFramework.2008', 
                    'urn:schema:Microsoft.Rtc.Management.Deploy.Topology.2008' AS t,
                    'urn:schema:Microsoft.Rtc.Management.Deploy.ServiceRoles.2008' AS fss)
SELECT
    ShareName = Data.value('(/AnchoredXml/Dictionary/Item/Value/t:Topology/t:Services/t:Service/fss:FileStoreService/@ShareName)[1]', 'varchar(50)')
FROM
    dbo.Item

就我而言,这会返回:

ShareName
-----------
lyncShare