問題描述
我正在使用 SQL Server 2008 解析 XML 文檔.我是一個完整的菜鳥,我想知道我是否可以從你們那里得到幫助.
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.
我有一個像下面這樣的 XML 文檔,我想獲取代碼"節點具有 val=5 的部分"節點.
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>
所以結果應該是:<代碼><節><代碼val=5/>...</section>
我試過這樣做,但沒有用:
I tried doing this, but it didn't work:
select @xml.query('/root/section')其中@xml.value('/root/section/code/@val,'int')='5'
我也試過這個:select @xml.query('/root/section')其中@xml.exist('/root[1]/section[1]/code[@val="1"])='1'
有什么想法嗎?提前致謝.
Any ideas? Thanks in advance.
推薦答案
你可以使用這個查詢:
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);
結果:
SectionAsXmlElement SectionAtr
------------------------------------------- ----------
<section atr="A"><code val="5" /></section> A
<section atr="C"><code val="5" /></section> C
這篇關于如何使用 sql server 在 XML 文檔中獲取包含具有給定屬性值的子節點的節點?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!