简体   繁体   English

如何使用DOM Java在xml中搜索子节点

[英]How to search for child nodes in xml using DOM Java

I have the following XML structure 我有以下XML结构

<CodeSnippet>
<Code id="code1">
<Tags>button java</Tags>
<Snippet>sample code</Snippet>
</Code>
<Code id="code2">
<Tags>eclipse jbutton java</Tags>
<Snippet>sample code</Snippet>
</Code>
<.....>
</CodeSnippet>

Now, I want to retrieve all the Snippet from the above xml when i search using Tags. 现在,当我使用标签搜索时,我想从上述xml中检索所有代码段。 For instance, if search for "java" then all the nodes that contain tags as "java" must return the snippet. 例如,如果搜索“ java”,则所有包含标签为“ java”的节点都必须返回代码段。

My search query is: 我的搜索查询是:

//Code/Tags[contains(concat(' ',/text(),' '), ' "+ searchTags[0] +" ')]";

Here, searchTags[0] contains "java". 在此,searchTags [0]包含“ java”。

My result set should contain the Snippets of the selected nodes ie code1 and code2 from above xml structure. 我的结果集应包含所选节点的代码段,即上述xml结构中的代码1和代码2。

试试这个表达式:

//Code/Tags[contains(., 'Java')]/../Snippet

For retrieving all the "Tags" containing "java", I used the below xpath expression, 为了检索包含“ java”的所有“标签”,我使用了以下xpath表达式,

//Code/Tags/text()[contains(., 'java')] //代码/标签/文本()[包含(。,'java')]

For retrieving all the "Snippet" related to the tags "java", I used below expression 为了检索与标签“ java”相关的所有“片段”,我使用了以下表达式

//Code/Tags[contains(./text(), 'java')]/parent::Code/Snippet/text() //代码/标签[包含(./text(),'java')] / parent :: Code / Snippet / text()

Thanks to @dfsq for helping me out with his expression. 感谢@dfsq帮助我表达他的观点。 Thanks a lot. 非常感谢。

You can write : 你可以写 :

//Tags//Snippet

If you used XPath 如果您使用XPath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM