2 Replies Latest reply: Aug 11, 2009 7:09 AM by 807588 RSS

    parse XML in inputstream, help!

    807588
      From a socket, I get a XML from the inputstream, in the XML it has many tages called "City", I want to take all the Citys out and put them in an array, there is something with my code, who can fix it?

      import java.io.*;
      import java.net.*;
      import javax.xml.parsers.DocumentBuilder;
      import javax.xml.parsers.DocumentBuilderFactory;
      import org.w3c.dom.Document;
      import org.w3c.dom.Node;
      import org.w3c.dom.NodeList;
      import org.xml.sax.InputSource;


      public class TCPClient { 
      public static void main(String argv[])throws Exception { 
      final int HTTP_PORT=80;

      Socket socket1 = new Socket("www.webservicex.net", HTTP_PORT);
      BufferedWriter out= new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream(), "UTF8"));
      // BufferedReader in= new BufferedReader(new InputStreamReader(socket1.getInputStream()));
      out.write("POST http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry HTTP/1.0\r\n");
      out.write("Host: www.webservicex.net\r\n");
      out.write("Content-Type: application/x-www-form-urlencoded\r\n");

      String body = "CountryName=china";
      out.write("Content-Length: " + body.length() + "\r\n");
      out.write("\r\n");

      out.write(body);
      out.flush();
           InputStreamReader inputStream = new InputStreamReader(socket1.getInputStream());
                System.out.println("Encoding is " + inputStream.getEncoding());
                BufferedReader in = new BufferedReader(inputStream);

      String xmlString="";
      String line;
      while((line=in.readLine())!=null){
           xmlString+=line;
      }




      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document document = db.parse(new InputSource(new StringReader(xmlString)));



      NodeList nl = document.getElementsByTagName("City");
      for (int count = 0; count < nl.getLength(); count++) {  
      Node n = nl.item(count);
      System.out.println(n);
      }


      out.close();
      in.close();



      }
      }