XML04-JDOM引入與DOM4J引入-----------------01

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>




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章