【问题标题】:Get XML element name and the attribute value using SQL XPATH query使用 SQL XPATH 查询获取 XML 元素名称和属性值
【发布时间】:2013-11-15 22:05:48
【问题描述】:

给定一个 XML 类型的字符串,例如

declare @xml xml

SET @xml = 
'<PO>
  <Amount type="approved">10.00</Amount>
  <Year type="">2013</Year>
  <GeneralNotes>
    <Note>
      <NoteText type="instruction">CallVendor</NoteText>
      <Date type="">1-1-2013</Date>
    </Note>
    <Note type="">
      <NoteText type="instruction">ShipNow</NoteText>
      <Date type="">2-2-2013</Date>
    </Note>
  </GeneralNotes>
</PO>'

我想获取每个元素及其属性(如果有的话)。我想要的输出(没有重复)是

ElementName   ElementAttribute

PO  
Amount   approved
Note     instruction

我试过类似这行的代码

SELECT T.doc.query('fn:local-name(.)') 
FROM @xml.nodes('PO//*[1]') AS T(doc)

这会带来重复,我不确定如何选择属性值。我只需要第一次出现(即GeneralNotes/Note[1])。我有一个包含许多其他元素名称的大文件,所以我不想单独解析它们。

【问题讨论】:

    标签: sql sql-server xml tsql sqlxml


    【解决方案1】:
    SELECT DISTINCT
           T.doc.value('fn:local-name(..)[1]', 'nvarchar(max)') as ElementName,
           T.doc.value('.', 'nvarchar(max)') as ElementAttribute 
    FROM @xml.nodes('PO//@*[1]') AS T(doc)
    WHERE T.doc.value('.', 'nvarchar(max)') <> ''
    

    结果:

    ElementName     ElementAttribute
    --------------- ----------------
    Amount          approved
    NoteText        instruction
    

    【讨论】:

      【解决方案2】:
      select distinct
          a.c.value('local-name(..)', 'nvarchar(max)') as ElementName,
          a.c.value('.', 'nvarchar(max)') as ElementAttribute
      from @xml.nodes('//@*[. != ""]') as a(c)
      

      sql fiddle demo

      【讨论】:

      • 非常有帮助,也是答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多