jdom操作xml:
解析过程:
//创建解析器
SAXBuilder buil=new
SAXBuilder();
//加载xml文件,返回的是Document对象
Document doc;
try
{
doc = buil.build(new
FileReader(new
File("myfile.xml")));
//获取xml根节点
Element root=doc.getRootElement();
//获取子节点
List <Element> list=root.getChildren("bookInfo",
root.getNamespace());
for(Element
e:list){
Element t=e.getChild("title",
e.getNamespace());
Element a=e.getChild("author",
e.getNamespace());
String bookName=t.getText();
String author=a.getText();
int
age=Integer.parseInt(a.getAttributeValue("age"));
String sex=a.getAttributeValue("sex");
System.out.println("书名:"+bookName+
" 作者名: "+author+"
age: "+age+" sex: "+sex);
}
}
catch
(FileNotFoundException e1) {
//
TODO
Auto-generated catch block
e1.printStackTrace();
}
catch
(JDOMException e1) {
//
TODO
Auto-generated catch block
e1.printStackTrace();
}
catch
(IOException e1) {
//
TODO
Auto-generated catch block
e1.printStackTrace();
}
}
创建XML过程:
//所有XML内存的根
Document document=null;
//创建<myfille></myfile>
Element root=new Element("myfile");
Element title=new Element("tile");
Element author=new Element("author");
//设置author的属性两种方法 第一种方法
author.setAttribute("age","11");
//第二种方法(使用对象的方式存入)
Attribute sex=new Attribute("sex", "22");
author.setAttribute(sex);
title.setAttribute("name","title");
root.addContent(title);
root.addContent(author);
//放入文本的两种方式
author.setText("jack");
author.addContent("jack");
title.addContent("java编程思想");
document=new Document(root);
//对文档单行getCompactFormat();或者多行.getPrettyFormat()显示的确定
Format f=Format.getPrettyFormat();
//必须用GB2312
f.setEncoding("GB2312");
//使用jdom封装好的进行开流
XMLOutputter out=new XMLOutputter(f);
try {
out.output(document, new FileWriter(new File("myfile.xml")));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end");
}
*/