简体   繁体   中英

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. 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!

The data is stored as a text string, so converting it to XML before parsing:

 <!-- 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".

Any idea where I'm going wrong?

proper XPath would be

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

sql fiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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