文件 - 如何通过名称获取标签的值? [英] Document - How to get a tag's value by its name?
本文介绍了文件 - 如何通过名称获取标签的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Java的DOM解析器来解析XML文件。
假设我有以下XML
<?xml version =1.0?>
< config>
< dotcms>
< endPoint> ip< / endPoint>
< / dotcms>
< / config>
< / xml>
我喜欢获取'endPoint'的值。我可以使用以下代码片段。 (假设我已经用DocumentBuilder解析了)
NodeList nodeList = this.doc.getElementByTagName(dotcms);
Node nValue =(Node)nodeList.item(0);
return nValue.getNodeValue();
可以通过字段名称获取字段的值吗?喜欢....
节点nValue = nodeList.getByName(endPoint)
这样的东西... ?
解决方案
您应该使用 XPath 这些任务:
// endPoint / text()
或:
/ config / dotcms / endPoint / text()
当然Java有一个内置的支持
$ pre>
XPath xpath = XPathFactory.newInstance()。newXPath();
XPathExpression expr = xpath.compile(// endPoint / text());
对象值= expr.evaluate(doc,XPathConstants.STRING);
I'm using Java's DOM parser to parse an XML file.
let's say I have the following XML
<?xml version="1.0"?>
<config>
<dotcms>
<endPoint>ip</endPoint>
</dotcms>
</config>
</xml>
I like to get the value of 'endPoint'. I can do it with the following code snippet. (assuming that I already parsed it with DocumentBuilder)
NodeList nodeList = this.doc.getElementByTagName("dotcms");
Node nValue = (Node) nodeList.item(0);
return nValue.getNodeValue();
Is it possible to get a value of a field by a field's name? Like....
Node nValue = nodeList.getByName("endPoint")
something like this...?
解决方案
You should use XPath for these sorts of tasks:
//endPoint/text()
or:
/config/dotcms/endPoint/text()
Of course Java has a built-in support for XPath:
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//endPoint/text()");
Object value = expr.evaluate(doc, XPathConstants.STRING);
这篇关于文件 - 如何通过名称获取标签的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文