XML parse file from HTTP

前端 未结 6 1537
广开言路
广开言路 2020-12-14 04:13

I have an XML file located at a location such as

http://example.com/test.xml

I\'m trying to parse the XML file to use it in my program with

6条回答
  •  失恋的感觉
    2020-12-14 04:32

    Here is the simple example for getting data form this string "http://www.gettingagile.com/feed/rss2/"

    public class MainClassXml {
    
        public static void main(String args[]) throws URISyntaxException,
                ClientProtocolException, IOException, MalformedURLException {
    
            String url = "http://www.gettingagile.com/feed/rss2/";
            System.out.println("Url is careated****");
            URL url2 = new URL(url);
            HttpGet httpGet = new HttpGet(url);
            HttpClient httpClient = new DefaultHttpClient();
    
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            System.out.println("Entity is*****" + entity);
            try {
                String xmlParseString = EntityUtils.toString(entity);
                System.out.println("This Stirng to be Pasrse***" + xmlParseString);
    
                HttpURLConnection connection = (HttpURLConnection) url2
                        .openConnection();
                InputStream inputStream = connection.getInputStream();
    
                DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                        .newInstance();
                DocumentBuilder documentBuilder = builderFactory
                        .newDocumentBuilder();
                Document document = documentBuilder.parse(inputStream);
                document.getDocumentElement().normalize();
    
                System.out.println("Attributes are***" + document.getAttributes());
    
                NodeList nodeList = document.getElementsByTagName("rss");
                System.out.println("This is firstnode" + nodeList);
                for (int getChild = 0; getChild < nodeList.getLength(); getChild++) {
    
                    Node Listnode = nodeList.item(getChild);
                    System.out.println("Into the for loop"
                            + Listnode.getAttributes().getLength());
                    Element firstnoderss = (Element) Listnode;
                    System.out.println("ListNodes" + Listnode.getAttributes());
                    System.out.println("This is node list length"
                            + nodeList.getLength());
    
                    Node Subnode = nodeList.item(getChild);
                    System.out.println("This is list node" + Subnode);
                    System.out.println("rss attributes***************");
                }
    
            } catch (Exception exception) {
    
                System.out.println("Exception is" + exception);
    
            }
        }
    

提交回复
热议问题