2013-11-15 81 views
4

給定一個XML類型的字符串,如獲取XML元素的名稱,並使用SQL XPath查詢

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])。我有許多其他元素名稱的大文件,所以我不想單獨解析它們。

回答

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 
+0

非常有幫助,謝謝! – rguy

0
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

+0

非常有幫助,也是答案。 – rguy