2015-11-08 34 views
0

解析XML,我需要在Java中创建一个应用程序,可以解析XML文档(我写的美元,我应该得到的回报率吧) http://www.bnr.ro/nbrfxrates.xml 我的代码现在的样子:从Java网址

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()); 
    } 
} 

和它不工作我得到一个解析错误。 你能告诉我它有什么问题吗? 谢谢

+0

你能分享确切的错误信息?顺便说一句。此代码不会编译,因为您有未处理的异常,并且您在静态方法中使用非静态变量。 –

回答

0

我试试你的代码..它没有编译,因为你在静态方法使用非静态变量,需要声明里面主要

网址,并获得您的结果需要增加变压器的对象

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()); 
-1

我找到了解决这个,这是一个工作代码:

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(); 



    } 
+0

为什么这是一个“解决方案”,“可以解析XML文档”,并避免“解析错误”?你根本没有做任何XML解析。 –