[英]Read XML file from URL
我嘗試從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)
您的計算機上沒有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());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.