我知道关于这个问题有很多答案,但是在我看来,所有答案都没有用。我想从这个链接阅读从欧洲央行的数据ECB。例如,如何读取其中time =“ 2015-02-27”的USD的“汇率”,以及如何读取所有90天的USD的“汇率”?
最简单的方法之一是使用DOM(文档对象模型)解析器。它将把您的xml文档加载到内存中,并将其变成由Nodes组成的树,以便您可以遍历它,以获取任何位置的任何节点的信息。它消耗内存,通常不如SAX解析器所喜欢。
这是一个例子:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class DomParsing {
public static final String ECB_DATAS ="C:\\xml\\eurofxref-hist-90d.xml";
public static void main(String argv[]) {
try {
File fXmlFile = new File(ECB_DATAS);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Cube");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("currency : " + eElement.getAttribute("currency") + " and rate is " + eElement.getAttribute("rate"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
应用于您的文件将产生以下结果:
货币:BGN汇率为1.9558
当前元素:立方体
货币:CZK汇率为27.797
当前元素:立方体
货币:DKK汇率为7.444
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句