如何使用Java获取XML中的值?
我已经尝试了很多次,但我不知道如何使用Java从XML中检索值。我尝试使用DOM和Xpath。请帮忙。我可以使用字符串编写器打印出XML,这样我就知道XML不是空的如何使用Java获取XML中的值?,java,xml,dom,xpath,xml-parsing,Java,Xml,Dom,Xpath,Xml Parsing,我已经尝试了很多次,但我不知道如何使用Java从XML中检索值。我尝试使用DOM和Xpath。请帮忙。我可以使用字符串编写器打印出XML,这样我就知道XML不是空的 Document doc = parseXML(connection.getInputStream()); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName
Document doc = parseXML(connection.getInputStream());
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("/xml_api_reply/weather/current_conditions/temp_f/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
Document doc=parseXML(connection.getInputStream());
doc.getDocumentElement().normalize();
System.out.println(“根元素:+doc.getDocumentElement().getNodeName());
XPath=XPathFactory.newInstance().newXPath();
XPathExpression expr=xPath.compile(“/xml\u api\u reply/weather/current\u conditions/temp\u f/text()”;
Object result=expr.evaluate(doc,XPathConstants.NODESET);
节点列表节点=(节点列表)结果;
对于(int i=0;i
XML的内容:
<xml_api_reply version="1">
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
<current_conditions>
<condition data="Clear"/>
<temp_f data="49"/>
<temp_c data="9"/>
</current_conditions>
</weather>
</xml_api_reply>
它似乎没有进入for循环,因为
节点
为空。您的XPath表达式的计算结果为temp\u f
下面的(不存在)文本节点。但是,您需要数据属性的值:
/xml_api_reply/weather/current_conditions/temp_f/@data
可能就是这样。您的XPath表达式的计算结果是
temp\u f
下面的(不存在的)文本节点。但是,您需要数据属性的值:
/xml_api_reply/weather/current_conditions/temp_f/@data
可能会成功。您是否尝试过此实现
您是否尝试过此实现
这与问题有什么关系?这与问题有什么关系?您可以编写一个简单的帮助器类来完成有关DOM的任务。看到这一点,您可以编写一个简单的助手类来完成围绕DOM的任务。看到这个了吗