简体   繁体   English

如何在java中搜索xml标记名称

[英]How Can I search for xml tag names in java

I need to search a specific xml node. 我需要搜索特定的xml节点。 I know part of its name but not the entire name... How can I get that element with part of the name? 我知道它的一部分名称,但不知道整个名字......我怎么能用名字的一部分得到那个元素?

I know it can be resolved using xpath, but I dont know how. 我知道它可以使用xpath解决,但我不知道如何。 For example...: 例如...:

<root>
<head/>
<body> <SuperAsdf> hi </SuperAsdf>
</body>
<root/>

I know that have to be a tag with "Super" but I dont know that it could have "Asdf", so I need a xPath expression to find all the tags with "Super". 我知道必须是“Super”的标签,但我不知道它可能有“Asdf”,所以我需要一个xPath表达式来查找所有带有“Super”的标签。

Also, what function supports xpaths in java? 另外,什么函数支持java中的xpath?

I'm using getElementsByTagName, but I read that it cant interpretate xpath. 我正在使用getElementsByTagName,但我读到它无法解释xpath。

Regular expressions would be overkill for this purpose. 为此目的,正则表达式将是过度的。 Just use an XPath expression like: 只需使用XPath表达式:

"//*[starts-with(local-name(), 'Super')]"

Regarding Java functions for XPath... see the code here for example, or look at the class XPathFactory . 关于XPath的Java函数...例如,请参阅此处的代码 ,或查看类XPathFactory

XPath 1.0 doesn't support regular expressions but you can still do something like this to achieve what you're trying to do (Using only XPath functions). 的XPath 1.0不支持正则表达式,但你仍然可以做一些像这样以达到你想要做的(只使用XPath函数)是什么。

Xpath 2.0 support regular expressions with functions like matches() and replace() (more information here ). Xpath 2.0支持带有matches()replace()等函数的正则表达式( 这里有更多信息)。

A regular expression in your case would look like: 您案例中的正则表达式如下所示:

(Super).*

You can use the XPath expression that LarsH suggested with the XPathAPI library ( javadoc ): 您可以使用LarsH为XPathAPI库javadoc )建议的XPath表达式:

List<Node> nodes =
    XPathAPI.selectListOfNodes(doc, "//*[starts-with(local-name(), 'Super')]")

If you have an XPath-2.0-compliant processor (for example Saxon) on your class path, JAXP and XPathAPI will pick it up and use it to select nodes. 如果类路径上有一个符合XPath-2.0标准的处理器(例如Saxon),JAXP和XPathAPI将选择它并使用它来选择节点。

(Disclaimer, I'm the author of the XPathAPI library.) (免责声明,我是XPathAPI库的作者。)

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

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