使用JDOM生成XML树和输出XML信息或文件

时间: 2007-12-17

  package cn.badboy;

import org.jdom.*;
import org.jdom.output.*;
import java.io.*;

public class MyWriter
{
 public static void main(String args[]) throws Exception
 {


  Document doc = new Document(); //建立文档对象


  Element root = new Element("users"); //建立根元素
  Element element = new Element("user"); //建立根元素的子元素
  Attribute attribute = new Attribute("company","boolean"); //建立一个新的属性complan,其值为boolean
  element.setAttribute(attribute); //为元素设置属性

  Element id_element = new Element("id");
  id_element.addContent("1");

  Element username_element = new Element("username");
  username_element.addContent("badboy");

  Element password_element = new Element("password");
  password_element.addContent("123456");

  element.addContent(id_element);
  element.addContent(username_element);
  element.addContent(password_element);

  root.addContent(element);
  doc.addContent(root);
  XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
  out.output(doc,System.out);

 }
}


你可能感兴趣的:(java,xml)