I'm using Java's DOM parser to parse an XML file.
我正在使用Java的DOM解析器来解析XML文件。
let's say I have the following XML
假设我有以下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)
我喜欢得到'endPoint'的价值。我可以使用以下代码片段来完成它。 (假设我已经用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...?
Node nValue = nodeList.getByName(“endPoint”)这样的东西......?
2 个解决方案
#1
5
You should use XPath for these sorts of tasks:
您应该将XPath用于这些类型的任务:
//endPoint/text()
or:
要么:
/config/dotcms/endPoint/text()
Of course Java has a built-in support for XPath:
当然Java有对XPath的内置支持:
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//endPoint/text()");
Object value = expr.evaluate(doc, XPathConstants.STRING);
#2
#1
5
You should use XPath for these sorts of tasks:
您应该将XPath用于这些类型的任务:
//endPoint/text()
or:
要么:
/config/dotcms/endPoint/text()
Of course Java has a built-in support for XPath:
当然Java有对XPath的内置支持:
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//endPoint/text()");
Object value = expr.evaluate(doc, XPathConstants.STRING);