posts - 0, comments - 77, trackbacks - 0, articles - 356
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

用jdom操纵xml文档例子

Posted on 2007-05-27 11:03 semovy 阅读(265) 评论(0)  编辑  收藏 所属分类: XML相关

package com.semovy.test;

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

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  //System.out.print(new MD5().getMD5ofStr(""));
  sampleJDom();
 }
   /*
    * jdom
    */
 public static void sampleJDom()
 {
  //新建文档对象
  Document doc = new Document();
  //新建根节点
  Element book = new Element("book");
  book.setAttribute("title", "Programming with Ajax");
  Element chapter1 = new Element("chapter");
  chapter1.setAttribute("name", "Chapter1 About Ajax");
  Element chapter2 = new Element("chapter");
  chapter2.setAttribute("name", "Chapter2 B/S Structure");
  Element section1 = new Element("section");
  section1.addContent("What is Ajax?");
  Element section2 = new Element("section");
  section2.addContent("Definiens of Ajax");
  Element section3 = new Element("section");
  section3.addContent("HTTP Protocal");
  Element section4 = new Element("section");
  section4.addContent("Web Design");
  //将子节点加入到父节点
  chapter1.addContent(section1);
  chapter1.addContent(section2);
  chapter2.addContent(section3);
  chapter2.addContent(section4);
  book.addContent(chapter1);
  book.addContent(chapter2);
  doc.addContent(book);
  //将文档输出到控制台
  XMLOutputter outputter = new XMLOutputter();
  try
  {
   outputter.output(doc, new FileOutputStream(new File("c:/a.xml")));
   System.out.println("输出到文件成功!");
   outputter.output(doc, System.out);
   System.out.println("输出到控制台!");
  }catch(IOException ex)
  {}
 }
}


只有注册用户登录后才能发表评论。


网站导航: