Jdom读写XML

阅读更多

1.maven引入jdom2

		
			org.jdom
			jdom2
			2.0.6
		

 2.实例

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

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class MemInfoParserJDOM {

	/**
	 * log4j2日志
	 */
	protected static Logger log = LogManager.getLogger();

	public static void main(String[] args) {
		String path = "/data/workspace/tec-demo/src/main/java/cn/tinyf/demo/xml/jdom/jdom-data.xml";
		MemInfoParserJDOM dj = new MemInfoParserJDOM();
		dj.createXml(path);
		dj.parserXml(path);
	}

	/**
	 * 生成XML
	 * 
	 * @param filePath
	 *            文件路径
	 */
	public void createXml(String filePath) {
		// 创建根节点
		Element root = new Element("MemInfo");
		root.setAttribute("class", "0501");
		// 创建第一个子节点
		root.addContent(createElementPerson(1, "James", 32));
		// 创建第二个子节点
		root.addContent(createElementPerson(2, "Kim", 38));
		// 创建第二个子节点
		root.addContent(createElementPerson(3, "Joe", 24));
		// 根节点添加到文档Document中
		Document document = new Document(root);
		try {
			// 输出到文件
			XMLOutputter XMLOut = new XMLOutputter();
			Format f = Format.getPrettyFormat();
			f.setEncoding("UTF-8");// default=UTF-8
			XMLOut.setFormat(f);
			XMLOut.output(document, new FileOutputStream(filePath));
		} catch (Exception e) {
			log.error(e);
		}
	}

	/**
	 * 创建学生子节点
	 * 
	 * @param no
	 *            学号
	 * @param name
	 *            姓名
	 * @param age
	 *            年龄
	 * @return
	 */
	private Element createElementPerson(int no, String name, int age) {
		Element person = new Element("person");
		person.setAttribute("no", no + "");
		// 姓名子节点
		Element nameE = new Element("name");
		nameE.addContent(name);
		person.addContent(nameE);
		// 年龄子节点
		Element ageE = new Element("age");
		ageE.addContent(age + "");
		person.addContent(ageE);
		// 返回节点
		return person;
	}

	/**
	 * 解析XML
	 * 
	 * @param filePath
	 *            文件路径
	 */
	public void parserXml(String fileName) {
		try {
			// 构建SAX解析器
			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 = persons.get(i);
				log.info("学号:{},姓名:{},年龄:{}", person.getAttribute("no").getValue(), person.getChildText("name"),
						person.getChildText("age"));
			}
		} catch (Exception e) {
			log.error(e);
		}
	}
}

 

你可能感兴趣的:(Jdom读写XML)