需要的包xmlbeans.jar,重要
对xml读写操作网上都有
java.lang.NoClassDefFoundError问题包不全造成的吧,domj4依赖4个包jaxen.jar,xalan.jar,xerces.jar,xml-apis.jar,下载domj4时在解压后的lib下
jdk1.6后已添加到其中xerces.jar,xml-apis.jar可删除
dom4j下载地址:http://sourceforge.net/projects/dom4j/
SAXReader saxreader = new SAXReader();
Document document = saxreader
.read(new URL(
"http://www.twototwo.cn/train/Service.aspx?format=xml&action=QueryTrainScheduleByTwoStation&key=80e12502-f08a-406b-b4c3-a682c2668937&startStation=%e5%8c%97%e4%ba%ac&arriveStation=%e4%b8%8a%e6%b5%b7&startDate=2013-03-15&ignoreStartDate=0&like=1&pageIndex=1&pageSize=2&more=0"));
Element root = document.getRootElement();
// System.out.println(root.getText());
System.out.println(root.getName());
Element main=(Element) root.elementIterator("Main").next();
// Element item=(Element) main.elementIterator(“Item”).next();
for (Iterator it=main.elementIterator(“Item”);it.hasNext()? {
for (Iterator it1=it.next().elementIterator(“CheCiMingCheng”);it1.hasNext()? {
System.out.println(it1.next().getText());
}
}
使用 XML Path Language (XPath) 语句 http://www.w3.org/TR/xpath/
// List le=document.selectNodes("/Response/Main/Item");
List le=document.selectNodes("//Item/@Id"); // //所有的含有id属性的item中的无素 //跳过父元素
for (Attribute element : le) {
System.out.println(element.getValue()); //@属性
}
// List le=document.selectNodes("//Item"); // //所有的item中的无素 //跳过父元素
// for (Element element : le) {
// System.out.println(element.valueOf("@Id")); //@属性
// }
public class TrainUtilsDom4jIterator {
/**
* 需要 jaxen-1.1-beta-7.jar
*
* @param args
* @throws DocumentException
* @throws MalformedURLException
*/
public static void main(String[] args) throws MalformedURLException,
DocumentException {
// TODO Auto-generated method stub
SAXReader saxreader = new SAXReader();
Document document = saxreader
.read(new URL(
"http://www.twototwo.cn/train/Service.aspx?format=xml&action=QueryTrainScheduleByTwoStation&key=80e12502-f08a-406b-b4c3-a682c2668937&startStation=%e5%8c%97%e4%ba%ac&arriveStation=%e4%b8%8a%e6%b5%b7&startDate=2013-03-15&ignoreStartDate=0&like=1&pageIndex=1&pageSize=2&more=0"));
//直接到此节点下
List<Element> le=document.selectNodes("/Response/Main/Item");
for (Iterator iterator = le.iterator(); iterator.hasNext();) {
Element element = (Element) iterator.next();
for(Iterator<Element> iterator1=element.elementIterator();iterator1.hasNext();){
element =iterator1.next();
System.out.println(element.getName()+" : "+element.getText());
}
}