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
1.2k views
in Technique[技术] by (71.8m points)

sql - Parsing OpenXML with multiple elements of the same name

I have a data structure as such:

<rootnode>
  <group>
    <id>1</id>
     <anothernode>first string</anothernode>
     <anothernode>second string</anothernode>
  </group>
 <group>
   <id>2</id>
     <anothernode>third string</anothernode>
     <anothernode>fourth string</anothernode>
  </group>
</rootnode>

And the following code:

EXEC sp_xml_preparedocument @index OUTPUT, @XMLdoc

SELECT *
FROM OPENXML (@index, 'rootnode/group')
WITH 
(
  id int 'id',
  anothernode varchar(30) 'anothernode'
)

which gives me the result

id | anothernode
————————————————
1  | first string
2  | third string

How can I get it to show this result instead where all four strings are showing instead?

id | anothernode
————————————————
1  | first string
1  | second string
2  | third string
2  | fourth string
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
SELECT *
FROM OPENXML (@index, 'rootnode/group/anothernode')
WITH 
(
  id int '../id',
  anothernode varchar(30) '.'
)

Or you can use the XML datatype instead like this:

SELECT G.N.value('(id/text())[1]', 'int') AS id,
       A.N.value('text()[1]', 'varchar(30)') AS anothernode
FROM @XMLDoc.nodes('rootnode/group') AS G(N)
  CROSS APPLY G.N.nodes('anothernode') AS A(N)

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

1.4m articles

1.4m replys

5 comments

57.0k users

...