Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

Parse XML in SQL Server

The XML looks like this:

<GespeicherteDaten>
    <strategieWuerfelFelder Type="strategieWuerfelFelder">
        <Felder X="3" Y="3" Z="3">
            <Feld X="1" Y="1" Z="1">
                <strategieWuerfelFeld Type="strategieWuerfelFeld">
                    <Name>Name</Name>
                    <Beschreibung>Test</Beschreibung>
                </strategieWuerfelFeld>
            </Feld>
            <Feld X="1" Y="1" Z="2">
                <strategieWuerfelFeld Type="strategieWuerfelFeld">
                    <Name>Name2</Name>
                    <Beschreibung>Test2</Beschreibung>
                </strategieWuerfelFeld>
            </Feld>
        </Felder>
    </strategieWuerfelFelder>
</GespeicherteDaten>'

My result table should contain the attributes Felder->X, Y, Z, Feld->X,Y,Z and Name.

Like:

Felder_X | Felder_Y | Felder_Z | Feld_X | Feld_Y | Feld_Z | Name

Is it possible to get this values directly from a query or stored procedure?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
DECLARE @xml xml
SET @xml = 
'<GespeicherteDaten>
<strategieWuerfelFelder Type="strategieWuerfelFelder">
    <Felder X="3" Y="3" Z="3">
        <Feld X="1" Y="1" Z="1">
            <strategieWuerfelFeld Type="strategieWuerfelFeld">
                <Name>Name</Name>
                <Beschreibung>Test</Beschreibung>
            </strategieWuerfelFeld>
        </Feld>
        <Feld X="1" Y="1" Z="2">
            <strategieWuerfelFeld Type="strategieWuerfelFeld">
                <Name>Name2</Name>
                <Beschreibung>Test2</Beschreibung>
            </strategieWuerfelFeld>
        </Feld>
    </Felder>
</strategieWuerfelFelder></GespeicherteDaten>'

SELECT 
    b.value('@X', 'int') as X
  , b.value('@Y', 'int') as Y
  , b.value('@Z', 'int') as Z
  , b.value('(./strategieWuerfelFeld/Name/text())[1]','Varchar(50)') as [Name]
  , b.value('../@X','int') as Felder_X
  , b.value('../@Y','int') as Felder_Y
  , b.value('../@Z','int') as Felder_Z  
FROM @xml.nodes('/GespeicherteDaten/strategieWuerfelFelder/Felder/Feld') as a(b) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...