簡體   English   中英

在Java中的URL處從XML讀取數據

[英]Read data from xml at url in java

我需要能夠使用以下xml從歐元中提取美元轉換: http : //www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

如果我手動下載xml並從那里解析為我需要的數據,那么我就可以使用它,但是我不確定如何直接從url中獲取它。

謝謝

如果我理解得很好,您將無法直接從URL獲取xml內容,對嗎?

如果是這樣,這可能對您有幫助。

// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));

// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());

它很好地適用於服務或獨立上下文,但是如果您嘗試從WEB層訪問XML,則可以考慮使用AJAX方法。

不能比這更容易:

package com.danielmarreco;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.net.URL;

public class Main {

    public static void main(String[] args) {
        try {
            InputStream is = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml").openStream();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(is);

            NodeList nodeList = doc.getElementsByTagName("Cube");

            for (int i = 0; i < nodeList.getLength(); i ++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    if(element.getAttribute("currency").equals("BRL")) 
                        System.out.println("1 EUR = " + element.getAttribute("rate") + " BRL");
                }
            }
        }
        catch (Exception e)        {
            e.printStackTrace();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM