您的位置:首页 > 编程语言

开源JDOM项目对xml编程

2014-12-09 12:32 507 查看
1.webproject中导入jdom.jar组件



2.写xml文件(例如在F盘创建一个my.xml)

public class JDOMWriter {

/**

* @param args

* @throws IOException

*/

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub

Document doc=new Document();

Element root=new Element("学生列表");

doc.setRootElement(root);

//创建学生元素

Element stu=new Element("学生");

stu.setAttribute("sno", "95001");

stu.addContent(new Element("姓名").addContent("zhou"));

stu.addContent(new Element("电话").addContent("110"));

root.addContent(stu);

Element stu2=new Element("学生");

stu2.setAttribute("sno", "95002");

stu2.addContent(new Element("姓名").addContent("hong"));

stu2.addContent(new Element("电话").addContent("120"));

root.addContent(stu2);

//删除子元素

//boolean cname=stu.removeChild("电话");

//创建姓名元素

/*Element name=new Element("姓名");

name.addContent("zhou");

Element tel=new Element("电话");

tel.addContent("110");

//在root下添加学生元素

root.addContent(stu);

stu.addContent(name);

stu.addContent(tel);

*/

/*Element stu2=new Element("学生");

stu2.setAttribute("sno", "95002");

//创建姓名元素

Element name2=new Element("姓名");

name2.addContent("hong");

Element tel2=new Element("电话");

tel2.addContent("119");

//在root下添加学生元素

root.addContent(stu2);

stu2.addContent(name2);

stu2.addContent(tel2);

*/

//xml输出工具类

XMLOutputter outputter=new XMLOutputter();

Format format=outputter.getFormat();

//设置xml编码

format.setEncoding("gb2312");

//设置xml缩进空格数,并且每个元素单独占一行

format.setIndent(" ");

//设置outputter格式

outputter.setFormat(format);

outputter.output(doc, new FileWriter("f:\\my.xml"));

}

}

3.读取f盘my.xml中的内容

public class JDOMRead {

/**

* @param args

* @throws IOException

* @throws JDOMException

*/

public static void main(String[] args) throws JDOMException, IOException {

// TODO Auto-generated method stub

SAXBuilder builder=new SAXBuilder();

Document doc=builder.build("f:\\my.xml");

Element root=doc.getRootElement();

//读取root下的所有子节点

List list=root.getChildren();

for(int i=0;i<list.size();i++)

{

Element person=(Element)list.get(i);

Element name=(Element)person.getChildren().get(0);

Element tel=(Element)person.getChildren().get(1);

//if(tel==null) tel=null;

System.out.println(name.getValue()+","+tel.getValue());

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: