在没有命名空间的SQL中解析XML

时间:2017-07-22 13:16:12

标签: sql sql-server xml

这个代码对于合适的人来说是自我解释的,但任何问题请大声说出来......

谢谢, 戴夫

DECLARE @XML XML

SET @XML = 
'<?xml version="1.0" encoding="utf-8"?>
<updates>
  <versions>
<installer type="A" Xversion="101" iniSizeInBytes="22480" dataSizeInBytes="23396349" msiSizeInBytes="4732928" />
<installer type="B" Yversion="201" iniSizeInBytes="22480" dataSizeInBytes="116687353" msiSizeInBytes="5807616" webconfigModifierSizeInBytes="11800" />
<installer type="A" Xversion="102" iniSizeInBytes="22480" dataSizeInBytes="23396349" msiSizeInBytes="4732928" />
<installer type="B" Yversion="202" iniSizeInBytes="22480" dataSizeInBytes="116687353" msiSizeInBytes="5807616" webconfigModifierSizeInBytes="11800" />
  </versions>
  <update setNumber="1" XVersion="101" YVersion="201">
    <detail Ref="1000">some detail info for 101 and 201</detail>
  </update>
  <update setNumber="2" XVersion="102" YVersion="202">
    <detail Ref="1001">some detail info for 102 and 202</detail>
  </update>
</updates>
'


SELECT
    r.value('@ref','NVARCHAR(250)') as 'Ref', --This is wrong, but you can probably see i'm wanting the value of Ref, eg 1000 for line 1, 1001 for line 2
    t.r.query('./detail').value('.','nvarchar(max)') as 'Detail'
FROM    @XML.nodes('/updates/update') AS t(r);

1 个答案:

答案 0 :(得分:0)

detail方法中需要value元素才能获取Ref属性中的值

SELECT
      r.value('@Ref','NVARCHAR(250)') as 'Ref',  -- It should be @Ref instead of @ref
      r.query('.').value('.','nvarchar(max)') as 'Detail'
FROM    @XML.nodes('/updates/update/detail') AS t(r);

注意:xml中的 Elementsattributes区分大小写,当xml @ref为{{1}时,您无法在查询中使用attribute }