import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class JDomDemo {
/**
* @param args
*/
public static void main(String[] args) {
String filePath = "F:\\mystudty\\resourses\\create_parser_xml.xml"; ?// 一定要写对前面的路径,根目录不对,是不会自动创建文件夹的。
File file = new File(filePath);
createXml(file);
parserXml(file);
}
/**
* 生成XML文件
* @param fileName
*/
public static void createXml(File file){
Element rootElement = new Element("persons");
Document document = new Document(rootElement);
for(int i=0;i<4;i++){
Element person = new Element("person");
Attribute attr = new Attribute("address", "北京");
person.setAttribute(attr);
rootElement.addContent(person);
Element name = new Element("name");
name.setText("vic_"+i);
person.addContent(name);
Element sex = new Element("sex");
sex.setText("男");
person.addContent(sex);
Element age = new Element("age");
age.setText("26");
person.addContent(age);
}
XMLOutputter XMLOut = new XMLOutputter();
try {
Format f = Format.getPrettyFormat();
f.setEncoding("UTF-8");
XMLOut.setFormat(f);
XMLOut.output(document, new FileOutputStream(file));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* 解析XML文件
* @param fileName
*/
public static void parserXml(File file){
try {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(file);
Element rootElement = document.getRootElement();
List persons = rootElement.getChildren("person");
for(int i=0;i<persons.size();i++){
Element person = (Element) persons.get(i);
List pros = person.getChildren();
for(int j=0;j<pros.size();j++){
Element element = (Element) pros.get(j);
System.out.print(element.getName()+":"+element.getValue());
System.out.print("\t");
}
System.out.println();
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
?