Posted on 2007-05-09 18:16
xiaoxiaoleemin 閱讀(1647)
評論(1) 編輯 收藏
在Java中用JDOM才操作xml文件很方便,需要的代碼量也比其它XML解析器要少的多。下面用一個簡單的例子來說明JDOM讀寫xml的最基本的步驟。假設(shè)已經(jīng)有如下的xml文件student.xml:
<Students>
<Student gender ="male">
<name>Tom</name>
<age>14</age>
<phone> 12345678</phone>
</Student>
</Students>
下面讀取該文件中的內(nèi)容并打印輸出:
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());
}
}
運(yùn)行輸出的結(jié)果如下:
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();
//縮進(jìn)的長度
fmt.setIndent(" ");
outputter.setFormat(fmt);
outputter.output(root.getDocument(), new BufferedWriter(new FileWriter("student.xml")));
}catch(IOException ioe)
{
ioe.printStackTrace();
}
現(xiàn)在的student.xml內(nèi)容如下:
<?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>