jdom生成和解析xml文件

[color=darkred]
package com.test;

import java.io.FileOutputStream;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

/**
* @说明 JDom生成解析XML
* @author cuisuqiang
* @version 1.0
* @since
*/
@SuppressWarnings("unchecked")
public class JDomDemo {
public static void main(String[] args) {
String file = "C:\\p.xml"; // 文件存放位置
JDomDemo dj = new JDomDemo();
dj.createXml(file);
dj.parserXml(file);
}
/**
* 生成XML
* @param filePath 文件路径
*/
public void createXml(String fileName) {
Element root = new Element("persons");
Document document = new Document(root);
Element person = new Element("person");
root.addContent(person);
Element name = new Element("name");
name.setText("java小强");
person.addContent(name);
Element sex = new Element("sex");
sex.setText("man");
person.addContent(sex);
Element age = new Element("age");
age.setText("23");
person.addContent(age);
XMLOutputter XMLOut = new XMLOutputter();
try {
Format f = Format.getPrettyFormat();
f.setEncoding("UTF-8");//default=UTF-8
XMLOut.setFormat(f);
XMLOut.output(document, new FileOutputStream(fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 解析XML
* @param filePath 文件路径
*/
public void parserXml(String fileName) {
try {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(fileName);
Element root = document.getRootElement();
List persons = root.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.println(element.getName() + ":" + element.getValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值