1、JDOM解析XML文件
private void parseXML() throws Exception {
SAXBuilder saxBuilder = new SAXBuilder();//创建SAXBuilder对象
FileInputStream in = new FileInputStream("books.xml");//创建输入流
Document document = saxBuilder.build(in);//加载xml文件
Element rootElement = document.getRootElement();//获取根节点
List<Element> bookList = rootElement.getChildren();//获取子节点
for(Element book:bookList){
Book bookEntity = new Book();
System.out.println("===开始解析第"+(bookList.indexOf(book)+1)+"本书===");
//如果知道属性名为id,获取属性值则是 book.getAttributeValue("id");
//首先解析属性,在不知道属性名称及个数的情况下,用getAttributes(),返回集合类型
List<Attribute> attrList = book.getAttributes();
for(Attribute attr:attrList){
String attrName = attr.getName();
String attrValue = attr.getValue(); //会自动去掉空格和换行,保留实际值
System.out.println("属性名:"+attrName+" 属性值:"+attrValue);
}
//获取节点的子节点
List<Element> bookChilds = book.getChildren();
for(Element child:bookChilds){
System.out.println("子节点名:"+child.getName()+" 子节点值:"+child.getValue());
System.out.println("===结束解析第"+(bookList.indexOf(book)+1)+"本书===");
System.out.println();
}
}
2、JDOM生成XML文件
private void createXML() throws Exception{
//生成根节点
Element rss = new Element("rss");
rss.setAttribute("version", "2.0");
//创建Document对象
Document document = new Document(rss);
Element channel = new Element("channel");
rss.addContent(channel);
Element title = new Element("title");
//title.setText("国内新闻");
title.addContent(new CDATA("<国内最新新闻>"));//这样子可以处理特殊字符
channel.addContent(title);
//生成XML文档
Format format = Format.getCompactFormat();
format.setEncoding("GBK");//设置编码
format.setIndent("");//设置换一行
XMLOutputter outputer = new XMLOutputter(format);
outputer.output(document, new FileOutputStream(new File("rss.xml")));
}
打开App,阅读手记