在忽略命名空间的同时查询XML?

时间:2013-06-26 23:43:46

标签: sql-server xml xpath

我正在尝试查询XML而忽略名称空间,因为结果集有多个名称空间。我已经进入了DataSets节点,但我无法弄清楚如何获取多个DataSourceName / CommandType / CommandText。理想情况下我想:

DataSetName   DataSourceName   CommandType      CommandText
SQLDS         SQLDS            StoredProcedure  ReportProc_aaaaa
SQLDS         SQLDS            StoredProcedure  ReportProc_lalala

非常感谢。

DECLARE @xmltable TABLE (myxml XML)
INSERT INTO @xmltable 
SELECT   
'<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
  <DataSources>
    <DataSource Name="SQLDS">
      <rd:DataSourceID>32e83b35-434d-4808-b685-ada14accd0e7</rd:DataSourceID>
      <DataSourceReference>SQLDS</DataSourceReference>
    </DataSource>
  </DataSources>
  <DataSets>
    <DataSet Name="SQLDS">
      <Query>
        <DataSourceName>SQLDS</DataSourceName>
        <CommandType>StoredProcedure</CommandType>
        <CommandText>ReportProc_ServerPerformanceGroup</CommandText>
      </Query>
    </DataSet>
    <DataSet Name="GroupDetails">
      <Query>
        <DataSourceName>SQLDS</DataSourceName>
        <CommandType>StoredProcedure</CommandType>
        <CommandText>ReportProc_lalala</CommandText>
      </Query>
    </DataSet>
  </DataSets>
</Report>'

SELECT myxml.value('(/*:Report/*:DataSets)[1]','varchar(100)') FROM @xmltable

2 个答案:

答案 0 :(得分:13)

使用nodes() Method (xml Data Type)将yoru XML碎化为行,并使用value() Method (xml Data Type)从XML中获取特定值。

select T1.N.value('@Name', 'nvarchar(128)') as DataSetName,
       T2.N.value('(*:DataSourceName/text())[1]', 'nvarchar(128)') as DataSourceName,
       T2.N.value('(*:CommandType/text())[1]', 'nvarchar(128)') as CommandType,
       T2.N.value('(*:CommandText/text())[1]', 'nvarchar(max)') as CommandText
from @xmltable as T
  cross apply T.myxml.nodes('/*:Report/*:DataSets/*:DataSet') as T1(N)
  cross apply T1.N.nodes('*:Query') as T2(N)

SQL Fiddle

答案 1 :(得分:0)

如何(未经测试)......

select
    T.c.value(N'DataSourceName', N'nvarchar(100)') as DataSourceName,
    T.c.value(N'CommandType',N'nvarchar(100)') as CommandType,
    T.c.value(N'CommandText', N'nvarchar(100)') as CommandText
  from
    @myxml.nodes(N'/Report/DataSets/DataSet/Query') T(c)