jdom 生成解析xml文件

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();
}
}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值