I'm working on parsing XML documents using SQL Server 2008. I'm a complete noob and I was wondering if I can get help from you guys.
I have an XML document like the one below and I want to get the "section" node where the "code" node has val=5.
<root>
<section>
<code val=6 />
...
</section>
<section>
<code val=5 />
...
</section>
<section>
<code val=4 />
...
</section>
</root>
So the result should be: <section> <code val=5 /> ... </section>
I tried doing this, but it didn't work:
select @xml.query('/root/section') where @xml.value('/root/section/code/@val,'int')= '5'
I also tried this: select @xml.query('/root/section') where @xml.exist('/root[1]/section[1]/code[@val="1"])= '1'
Any ideas? Thanks in advance.
You could use this query:
DECLARE @x XML=N'
<root>
<section atr="A">
<code val="5" />
</section>
<section atr="B">
<code val="6" />
</section>
<section atr="C">
<code val="5" />
</section>
</root>';
SELECT a.b.query('.') AS SectionAsXmlElement,
a.b.value('@atr','NVARCHAR(50)') AS SectionAtr
FROM @x.nodes('/root/section[code/@val="5"]') a(b);
Results:
SectionAsXmlElement SectionAtr
------------------------------------------- ----------
<section atr="A"><code val="5" /></section> A
<section atr="C"><code val="5" /></section> C
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다