简体   繁体   English

使用SQL从XML字段中提取具有异常XML的值

[英]Extracting values from XML field with unusual XML using SQL

Hoping someone can help - 希望有人可以帮助-

The XML format was put together with a very simple syntax, but for some reason I'm struggling to parse it using a standard 'value' type query. XML格式使用非常简单的语法组合在一起,但是由于某种原因,我正在努力使用标准的“值”类型查询来解析它。 I'm experienced with SQL, but only have limited experience in XML, and after 2 hours of frustration and much Googling, I thought I'd ask for my own sanity! 我对SQL有经验,但是对XML的经验有限,经过2个小时的挫折和大量的Google搜索,我想我会要求自己的理智!

The data is stored as a text string, so converting it to XML before parsing: 数据存储为文本字符串,因此在解析之前将其转换为XML:

 <!-- Data config file --> 
 <Config>   
  <!-- keys-->
  <foo value="bar"/>
  <foo1 value="bar1"/>
  <big_foo value="bar/bar.com"/>
  <other value="f00"/>

The query I'm using is: 我正在使用的查询是:

SELECT  
 col.value('foo1[0]', 'nvarchar(max)') as VALUE
 from
(
select  
    CAST((SELECT TOP 1 xml_text FROM dbo.xml_lookup)AS XML)
 as Col)x

but this returns NULL rather than the expected "bar1". 但这将返回NULL而不是预期的“ bar1”。

Any idea where I'm going wrong? 知道我哪里出错了吗?

proper XPath would be 正确的XPath将是

col.value('(Config/foo1)[1]/@value', 'nvarchar(max)')

sql fiddle demo sql小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM