簡體   English   中英

使用SQL XPATH查詢獲取XML元素名稱和屬性值

[英]Get XML element name and the attribute value using SQL XPATH query

給定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] )。 我有一個包含許多其他元素名稱的大文件,因此我不想單獨解析它們。

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
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小提琴演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM