我需要在java中创建一个可以解析xml doc的应用程序(我写的是USD,我应该得到它的回报率) http://www.bnr.ro/nbrfxrates.xml 我的代码现在看起来像:
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)
我尝试你的代码..它没有编译,因为你在静态方法中使用非静态变量,你需要在main中声明url
要获得结果,您需要添加变换器对象
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 :(得分:-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();
}