简体   繁体   中英

Java parsing xml from url

I need to create a application in java that can parse the xml doc (i write USD and i should get in return the rate for it) http://www.bnr.ro/nbrfxrates.xml My Code right now looks like:

package bnr;

import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;


public class Bnr {

    /**
     * @param args the command line arguments
     */

    String url = "http://www.bnr.ro/nbrfxrates.xml";
    public static void main(String[] args) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new URL(url).openStream());
    }
}

and its not working i get a parse error. Can you please tell me what is wrong with it. Thank you,

i try your code .. it didn't compile because you use a non-static variable in static method, you need to declare url inside main

and to get your result you need to add transformer object

public static void main(String[] args) {
    try {
        String url="http://www.bnr.ro/nbrfxrates.xml";
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new URL(url).openStream());
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        String output = writer.getBuffer().toString();
        System.out.println(output.trim()); 

I found the solution to this this is a working code:

public static void main(String[] args) throws SAXException, IOException  {
        URL oracle = new URL("http://www.bnr.ro/nbrfxrates.xml");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();



    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM