www.jdom.org----下载jar包并导入项目(导入源码)
package com.java.xml;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
public class JDOM01 {
public static void main(String[] args) {
Element student=new Element("student");
Attribute id=new Attribute("id","001");
Attribute aa=new Attribute("aa","xx");
student.setAttribute(id);
student.setAttribute(aa);
Element name=new Element("name");
name.setText("张三");
student.addContent(name);
Element sex=new Element("sex");
sex.setText("男");
student.addContent(sex);
Element age=new Element("age");
sex.setText("20");
student.addContent(age);
Document document=new Document(student);
XMLOutputter out=new XMLOutputter();
out.setFormat(out.getFormat().setEncoding("UTF-8"));
try {
out.output(document, new FileOutputStream("src/student04.xml"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
结果:生成XML
<?xml version="1.0" encoding="UTF-8"?>
<student id="001" aa="xx"><name>张三</name><sex>20</sex><age /></student>
本文介绍了一种使用Java库JDOM创建XML文件的方法。通过示例代码展示了如何定义XML文档结构,包括设置元素属性、添加子元素及文本内容,并最终将构建好的文档输出为XML文件。
558

被折叠的 条评论
为什么被折叠?



