使用xml中包含的样式表/命名空间查询XML

时间:2014-09-28 19:05:48

标签: sql-server xml sql-server-2012

我已经尝试了几种方法来查询这些数据,但还没有成功。我在SQL Server 2012上。任何帮助都将不胜感激。

<NewDataSet>
  <Table>
    <_x005B_M_x005D_._x005B_SEQID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:short">200</_x005B_M_x005D_._x005B_SEQID_x005D_>
    <_x005B_M_x005D_._x005B_CPID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1002</_x005B_M_x005D_._x005B_CPID_x005D_>
  </Table>
</NewDataSet>

2 个答案:

答案 0 :(得分:1)

如果您希望从中获得更多信息,将会有所帮助,但这是一个开始,假设XML的每个元素代表一行:

DECLARE @SampleData XML = N'
<NewDataSet>
  <Table>
    <_x005B_M_x005D_._x005B_SEQID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:short">200</_x005B_M_x005D_._x005B_SEQID_x005D_>
    <_x005B_M_x005D_._x005B_CPID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1002</_x005B_M_x005D_._x005B_CPID_x005D_>
  </Table>
</NewDataSet>
';

DECLARE @Delim VARCHAR(50) = '._x005B_';
DECLARE @DelimLen INT = LEN(@Delim);

;WITH cte AS
(
   SELECT  xrow.value('local-name(.)', 'VARCHAR(50)') AS [ElementName],
           xrow.value('declare namespace xsi="http://www.w3.org/2001/XMLSchema-instance"; (./@xsi:type)[1]', 'VARCHAR(50)') AS [xsi:type],
           xrow.value('./text()[1]', N'VARCHAR(50)') AS [ElementValue]
   FROM    @SampleData.nodes('NewDataSet/Table/*') t(xrow)
)
SELECT *,
       SUBSTRING(
          cte.ElementName,
          CHARINDEX(@Delim, cte.ElementName) + @DelimLen,
          CHARINDEX('_',
                    cte.ElementName,
                    CHARINDEX(@Delim, cte.ElementName) + @DelimLen + 1) - 
                       (CHARINDEX(@Delim, cte.ElementName) + @DelimLen)
                   ) AS [RowType]
FROM cte;

输出:

ElementName                           xsi:type    ElementValue  RowType
_x005B_M_x005D_._x005B_SEQID_x005D_   xs:short    200           SEQID
_x005B_M_x005D_._x005B_CPID_x005D_    xs:string   1002          CPID

答案 1 :(得分:0)

declare @demo xml = '<NewDataSet>
  <Table>
    <_x005B_M_x005D_._x005B_SEQID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:short">200</_x005B_M_x005D_._x005B_SEQID_x005D_>
    <_x005B_M_x005D_._x005B_CPID_x005D_ xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1002</_x005B_M_x005D_._x005B_CPID_x005D_>
  </Table>
</NewDataSet>'

select t.r.value('(./*[local-name()=''_x005B_M_x005D_._x005B_SEQID_x005D_'']/text())[1]','integer') seqid
, t.r.value('(./*[local-name()=''_x005B_M_x005D_._x005B_CPID_x005D_'']/text())[1]','nvarchar(128)') cpid
from @demo.nodes('/*/*') t(r) 

SQL小提琴:http://sqlfiddle.com/#!6/d41d8/21769