Posted on 2007-05-09 18:16
xiaoxiaoleemin 阅读(1635)
评论(1) 编辑 收藏
在Java中用JDOM才操作xml文件很方便,需要的代码量也比其它XML解析器要少的多。下面用一个简单的例子来说明JDOM读写xml的最基本的步骤。假设已经有如下的xml文件student.xml:
<Students>
<Student gender ="male">
<name>Tom</name>
<age>14</age>
<phone> 12345678</phone>
</Student>
</Students>
下面读取该文件中的内容并打印输出:
SAXBuilder builder = new SAXBuilder(false);
Document document = null;
try {
document = builder.build("student.xml");
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Element root = document.getRootElement();
List students = root.getChildren();
for( int i=0; i<students.size(); i++)
{
Element student = (Element)students.get(i);
System.out.println("Attribute Gender :" + student.getAttributeValue("gender"));
List children = student.getChildren();
for( int j=0; j<children.size(); j++)
{
Element child = (Element)children.get(j);
System.out.println("Element name: "+ child.getName() );
System.out.println("Element value: " + child.getText());
}
}
运行输出的结果如下:
Attribute Gender :male
Element name: name
Element value: Tom
Element name: age
Element value: 14
Element name: phone
Element value: 12345678
下面插入一个student记录,然后保存到student.xml文件中:
//inset a record of student
Element student = new Element("Student");
student.setAttribute("gender", "female");
student.addContent(new Element("name").setText("Mary"));
student.addContent(new Element("age").setText("18"));
student.addContent(new Element("phone").setText("42483433"));
document.getRootElement().addContent(student);
try{
XMLOutputter outputter = new XMLOutputter();
Format fmt = Format.getPrettyFormat();
//缩进的长度
fmt.setIndent(" ");
outputter.setFormat(fmt);
outputter.output(root.getDocument(), new BufferedWriter(new FileWriter("student.xml")));
}catch(IOException ioe)
{
ioe.printStackTrace();
}
现在的student.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<Students>
<Student gender="male">
<name>Tom</name>
<age>14</age>
<phone>12345678</phone>
</Student>
<Student gender="female">
<name>Mary</name>
<age>18</age>
<phone>42483433</phone>
</Student>
</Students>