[英]How do you get a node that contains a child node with a given attribute value in an XML document using sql server?
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. 我正在使用SQL Server 2008解析XML文档。我是一个完整的菜鸟,我想知道我是否能得到你们的帮助。
I have an XML document like the one below and I want to get the "section" node where the "code" node has val=5. 我有一个类似下面的XML文档,我想得到“section”节点,其中“code”节点有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>
所以结果应该是:
<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'
我也试过这个:
select @xml.query('/root/section') where @xml.exist('/root[1]/section[1]/code[@val="1"])= '1'
Any ideas? 有任何想法吗? Thanks in advance.
提前致谢。
而不是where
你可以在XPath谓词应用约束:
@xml.query('/root/section[code/@val=5]')
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.