我尝试从https://www.nbp.pl/kursy/xml/c001z020102.xml读取xml文件。
我在数字上添加了Sout,以观察进度。
public void wypisanie() throws Exception
{
URL url = new URL("https://www.nbp.pl/kursy/xml/c001z020102.xml");
System.out.println("1");
URLConnection urlConnection = url.openConnection();
System.out.println("2");
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
System.out.println("3");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
System.out.println("4");
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
System.out.println("5");
Document doc1 = dBuilder.parse( in );
System.out.println("6");
Element element1 = doc1.getDocumentElement();
System.out.println("7");
NodeList nodes1 = element1.getChildNodes();
System.out.println("8");
for (int i = 0; i < nodes1.getLength(); i++) {
System.out.println("" + nodes1.item(i).getTextContent());
}
}
这是结果:
1
2
https://www.nbp.pl/kursy/xml/c001z020102
我的目标是从此URL获取美元汇率。有人有其他想法我应该怎么做?
编辑: 我尝试使用其他网址,如下所示: https://www.w3schools.com/xml/plant_catalog.xml 和程序工作。那么“旧”网址有什么问题呢? https://www.nbp.pl/kursy/xml/c001z020102.xml
“旧”网址的结果
1
2
3
4
5
C:\Users\user\IdeaProjects\NBP\untitled\abch.dtd (The system cannot find the file specified)
答案 0 :(得分:0)
您的计算机上没有DTD文件。
尝试一下:
public void wypisanie() throws Exception {
URL url = new URL("https://www.nbp.pl/kursy/xml/c001z020102.xml");
System.out.println("1");
URLConnection urlConnection = url.openConnection();
System.out.println("2");
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
System.out.println("3");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setNamespaceAware(true);
dbf.setFeature("http://xml.org/sax/features/namespaces", false);
dbf.setFeature("http://xml.org/sax/features/validation", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
System.out.println("4");
DocumentBuilder dBuilder = dbf.newDocumentBuilder();
System.out.println("5");
Document doc1 = dBuilder.parse(in);
System.out.println("6");
Element element1 = doc1.getDocumentElement();
System.out.println("7");
NodeList nodes1 = element1.getChildNodes();
System.out.println("8");
for (int i = 0; i < nodes1.getLength(); i++) {
if ("pozycja".equals(nodes1.item(i).getNodeName())) {
System.out.println("" + nodes1.item(i).getTextContent());
}
}
}