dom4j 生成 xml ,解析xml
xml 生成
Document dod =DocumentHelper.createDocument(); //建立xml
Element ele = dod.addElement("student");
Element tet = ele.addElement("yyy");
Element nameElement = tet.addElement("name");
nameElement.addText("sss");
Element tets = ele.addElement("tets");
tets.addText("sssdd");
/* System.out.println(dod.asXML());*/ //生成 xml 字串
try {
Writer fileWriter = new FileWriter("c:\\module.xml");
//dom4j提供了專門寫入檔案的物件XMLWriter
XMLWriter xmlWriter = new XMLWriter(fileWriter);
xmlWriter.write(dod);
xmlWriter.flush();
xmlWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
xml 解析
SAXReader reader =new SAXReader();
try {
Document document = reader.read(new File("c:/module.xml"));
Element Ele = document.getRootElement();
System.out.println(Ele.getName());
Element fooElement;
for(Iterator i=Ele.elementIterator("yyy");i.hasNext();){
fooElement=(Element)i.next();
System.out.println("ss:"+fooElement.elementText("name"));
}
} catch (DocumentException e) {
e.printStackTrace();
}
}