<?xml version="1.0" encoding="gb2312"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<students>
<student sn="01">
<name>张三</name>
<age>18</age>
</student>
<student sn="02">
<name>李四</name>
<age>20</age>
</student>
</students>
JDOM对文件操作
package com.ibm.xml;
import java.io.File;
import java.io.IOException;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
* JDOM对文件做增加、修改、删除
* @author Administrator
*
*/
public class JDOMConvert
{
public static void main(String[] args)
{
SAXBuilder saxBuilder=new SAXBuilder();
try
{
Document doc=saxBuilder.build(new File("students.xml"));
Element eltStu=new Element("student");
Element eltName=new Element("name");
Element eltAge=new Element("age");
eltName.setText("王五");
eltAge.setText("19");
eltStu.addContent(eltName);
eltStu.addContent(eltAge);
eltStu.setAttribute("sn","03");
Element root=doc.getRootElement();
root.addContent(eltStu);
root.removeChild("student");
root.getChild("student").getChild("age").setText("22");
XMLOutputter xmlOut=new XMLOutputter();
Format fmt=Format.getPrettyFormat();
fmt.setIndent(" ");
fmt.setEncoding("gb2312");
xmlOut.setFormat(fmt);
try
{
xmlOut.output(doc,System.out);
}
catch (IOException e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
catch (JDOMException e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
}
catch (IOException e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}