在sql server 2012中读取xml结构

时间:2014-11-12 13:49:15

标签: sql sql-server xml

示例Xml结构

<?xml version="1.0" encoding="UTF-8"?>
<XmlSerializableHashtable xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <Entries>
      <Entry>
         <key xsi:type="xsd:string">col1</key>
         <value xsi:type="xsd:string">500</value>
      </Entry>
      <Entry>
         <key xsi:type="xsd:string">col2</key>
         <value xsi:type="xsd:string">0/60,1/1000</value>
      </Entry>
      <Entry>
         <key xsi:type="xsd:string">col3</key>
         <value xsi:type="xsd:string">localhost</value>
      </Entry>
   </Entries>
</XmlSerializableHashtable>

不,我正在尝试获取key为col3的值

我正在尝试使用Xquery

Declare @x xml;
Set @x = (Select valuefrom sometable)

Select @x.query('/Entries/Entry/')

1 个答案:

答案 0 :(得分:0)

此查询将有所帮助。

DECLARE @xmlData AS XML
DECLARE @sRawData AS VARCHAR(2000)

SET @sRawData = '<?xml version="1.0" encoding="UTF-8"?>
<XmlSerializableHashtable xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <Entries>
      <Entry>
         <key xsi:type="xsd:string">col1</key>
         <value xsi:type="xsd:string">500</value>
      </Entry>
      <Entry>
         <key xsi:type="xsd:string">col2</key>
         <value xsi:type="xsd:string">0/60,1/1000</value>
      </Entry>
      <Entry>
         <key xsi:type="xsd:string">col3</key>
         <value xsi:type="xsd:string">localhost</value>
      </Entry>
   </Entries>
</XmlSerializableHashtable>'

SET @xmlData = CAST(@sRawData AS XML)

SELECT MainDataCenter.Col.value('(key)[1]','varchar(max)') AS [key]
      ,MainDataCenter.Col.value('(value)[1]','varchar(max)') AS Value
FROM @xmlData.nodes('/XmlSerializableHashtable/Entries/Entry') AS MainDataCenter(Col)
WHERE MainDataCenter.Col.value('(key)[1]','varchar(max)') = 'col3'