您的位置:首页 > 编程语言 > Java开发

【Java开发】--jdom解析xml-创建xml

2015-10-29 17:44 495 查看
JDOM解析XMl的方法

package com.test.jdom;

import java.io.FileWriter;

import org.jdom2.Comment;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

/**
*
* 项目名称: JDOM对XML一系列操作
* 包:      com.test.jdom;
* 类名称:   test.java
* 类描述:   JDOM对XML一系列操作
* 创建人:   Anny
* 创建时间: 2015-10-29
* 版本:    [v1.0]
*
*/
public class test
{
@SuppressWarnings("null")
public static void createXML()
{
/**
* Element.setAttribute 为元素添加信息

Element.addContent(String,String) 为元素添加子元素内容,也可以直接添加另一个元素节点

Document.setRootElement(Element) 为文档添加根元素

XMLOutputter.output(Document,FileWriter) 将Docuemnt写入到FileWriter文件流中
*/
Document mydoc = new Document();
// 创建元素person1
Element person1 = new Element("person");
person1.setAttribute("id", "ID001");    //为persion元素创建id
person1.addContent(new Comment("this is person1")); //为persion增加注释
person1.addContent(new Element("name").setText("Anny"));
person1.addContent(new Element("age").setText("24"));
person1.addContent(new Element("sex").setText("girl"));
//嵌套子元素
Element address1 = new Element("address");
address1.setAttribute("zone", "province");
address1.addContent("Heilongj");

person1.addContent(address1);

// 创建元素person2
Element person2 = new Element("person");
person2.setAttribute("id", "ID002");    //为persion元素创建id
person2.addContent(new Comment("this is person2")); //为persion增加注释
person2.addContent(new Element("name").setText("Lizhen"));
person2.addContent(new Element("age").setText("23"));
person2.addContent(new Element("sex").setText("boy"));
//嵌套子元素
Element address2 = new Element("address");
address2.setAttribute("zone", "province");
address2.addContent("Heilongj");

person2.addContent(address2);

// 在doc中添加元素Person
Element info = new Element("information");
info.addContent(person1);
info.addContent(person2);
mydoc.setRootElement(info);

saveXML(mydoc);

}

private static void saveXML(Document doc)
{
// 将doc对象输出到文件
try {
// 创建xml文件输出流
XMLOutputter xmlopt = new XMLOutputter();
// 创建文件输出流
FileWriter writer = new FileWriter("person.xml");
// 指定文档格式
Format fm = Format.getPrettyFormat();
// fm.setEncoding("GB2312");
xmlopt.setFormat(fm);
// 将doc写入到指定的文件中
xmlopt.output(doc, writer);
writer.close();
}catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
createXML();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: