XML解析入门之JDOM(三)

 

package com.liuc.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

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

public class XMLInsert {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		insert(new File("person.xml"));
	}

	private static void insert(File file) {
		try {
			SAXBuilder sax=new SAXBuilder();
			Document doc=sax.build("person.xml");
			if (doc!=null) {
				if (doc.hasRootElement()) {
					Element root=doc.getRootElement();
					Element person=new Element("person");
					root.addContent(person);
					Attribute attr=new Attribute("perid", "1003");//创建属性
					person.setAttribute(attr);//添加属性
					Element name=new Element("name");
					name.setText("wangwu");
					person.addContent(name);
					Element age=new Element("age");
					age.setText("25");
					person.addContent(age);
					Element address=new Element("address");
					address.setText("saoziying");
					person.addContent(address);
					Element sex=new Element("sex");
					sex.setText("男");
					person.addContent(sex);
					XMLOutputter outp=new XMLOutputter();//用于输出JDOM文档
					Format format=Format.getPrettyFormat();//格式化文档
					format.setEncoding("UTF-8");
					outp.setFormat(format);
					FileOutputStream fos=new FileOutputStream("person.xml");
					outp.output(doc, fos);
				}
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
XML文件
<?xml version="1.0" encoding="UTF-8"?>
<persons>
  <person perid="1001">
    <name>zhangsan</name>
    <age>89</age>
    <address>安徽淮北</address>
    <sex>男</sex>
  </person>
  <person perid="1002">
    <name>lisi</name>
    <age>56</age>
    <address>北京海淀</address>
    <sex>女</sex>
  </person>
</persons>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值