我有以下代码
protected static final String TAG_numFound = "numFound"; //
Document street_xmlDoc = GetXMLDocument(street_url);
Element results = street_xmlDoc.getDocumentElement();
//numFound
Node numFoundNode = results.getElementsByTagName(TAG_numFound).item(0);
String numFound = numFoundNode.getNodeValue() + "(" + numFoundNode.getNodeName() + ")";
和以下 XML
<results>
<numFound>1</numFound>
<QTime>66</QTime>
<result>
<distance>0.0</distance>
<name>Agua</name>
</result>
</results>
在 numFound 字符串变量中我得到“null(numFound)” 我不明白为什么我没有得到“1(numFound)”。 我做错了什么?
最佳答案
您可以使用 XPath
来获取值,这对于您的代码的 future 读者来说可能会更清楚:
final Document document = //build your document
final XPath xPath = XPathFactory.newInstance().newXPath();
final XPathExpression expression = xPath.compile("//numFound/text()");
final Number output = (Number) expression.evaluate(document, XPathConstants.NUMBER);
System.out.println(output);
输出:
1.0
关于java - 无法获取 XML 标记值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15625335/