Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.8k views
in Technique[技术] by (71.8m points)

Read XML content from public URL Java

I'm trying to read XML content from a public URL source file, which can be read through its URL.

This XML: https://www.bnr.ro/nbrfxrates.xml

This URL blocks you if you make too many requests, so I made my local file.xml to parse at first. Now I'm not sure how I can read the XML from URL and not my local file. Does anyone knows? Can you help me, please? (I saw different versions on internet but I'm not sure which is the best, because of the "block" part I can't make to many requests)

Here is my code for xml parse:

public void parse(){
        

        try {
            //here I parse XML from my local file
            //this should be replaced with the URL 
            File inputFile = new File("xmlFile.xml");
            
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();
           
            Element root = doc.getDocumentElement();
            NodeList nList = doc.getElementsByTagName("Rate");

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
              
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;

                    
                    System.out.println("coin: "+eElement.getAttribute("currency")+" value: "+eElement.getTextContent());
                   
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
     
}

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
by (100 points)

In case anyone want to check C# based solution, check
Read XML in C# or XML Interview Question and answers
Thanks

Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...