您的位置:首页 > 其它

使用Jdom解析XML

2006-01-11 12:35 489 查看
使用Jdom解析XML的代码要比使用dom解析XML的代码简洁!
package jdomtest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
//下面是引用到JDOM中的类
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
public class JDOM {
public JDOM() {
} public static void main(String[] args) {
JDOM jdom = new JDOM();
String xmlpath="1.xml";
SAXBuilder builder=new SAXBuilder(false);
try { Document doc=builder.build(xmlpath);
Element rss=doc.getRootElement();
Element channel =rss.getChild("channel");
System.out.println(channel.getChildText("title")) ;
List itemlist=channel.getChildren("item");
for (Iterator iter = itemlist.iterator(); iter.hasNext();) {
Element item = (Element) iter.next();
String title=item.getChildTextTrim("title");
System.out.println(title);
String url=item.getChildTextTrim("link");
System.out.println(url);
String pubdate=item.getChildTextTrim("pubDate");
System.out.println(pubdate); String comments=item.getChildTextTrim("comments");
System.out.println(comments.length());
String description=item.getChildTextTrim("description");
System.out.println(description);
// item.getChild("comments").setText("评论地址"); }
XMLOutputter outputter=new XMLOutputter("",true,"GB2312");
//outputter.output(doc,new FileOutputStream(xmlpath));
outputter.setTextTrim(true); outputter.output(doc,System.out);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: