日期:2014-05-20  浏览次数:20677 次

XML的字符串分析的问题
我现在有了一个XML内容的字符串,我想把其中的City节点都取出来,但怎么都做不对,请教
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;
}
  System.out.println(xmlString);
 
   
/* 这块到底该怎么写? 
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();  
 
 
 */
  }  
  }  


------解决方案--------------------
注:以下方式基于dom4j
1.读取xml文件,返回一个document对象
2.document.selectNodes("/这里面给XPath");返回一个list数组
3.迭代这个数组 在这个循环里面你可以操作你迭代的对象 用这个对象
的getStringValue()可以获得值
elementText(“子元素名字”)可以获得当前子元素的值
等等 里面有很多方法 自己点一下 就知道啦