jdom学习(1)建立XML文件(转)

JDOM 是一个开源的纯java API,用于快速开发 XML 应用程序,JDOM将XML文档表示为树,包括元素、属性、说明、处理指令、文本节点、CDATA段,等等。JDOM可以随时访问树中的任意部分。树中所有不同节点均为具体的类。在http://jdom.org可以下载JDOM的最新版本。下载后解压,JDOM的jar文件就是build目录下的文件jdom.jar,将之加入类路径。
jdom中最重要的一个包是org.jdom,其中主要有以下类用来进行xml文档的操作: 
Attribute 
CDATA 
Comment 
DocType 
Document 
Element 
EntityRef 
Namespace 
ProcessingInstruction 
Text 
看看jdom怎样创建xml文档:
import java.io.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.input.*;
import org.jdom.output.*;
public class test1 {    
      public void BuildXMLDoc() throws IOException, JDOMException {  
      Element root, e1, e2;        
      Document Doc;        
      root = new Element("employees_information");//首先建立根元素
      DocType type=new DocType("employees_information","employees.dtd");//文档类型
      Doc = new Document(root,type);//然后用root创建XML文档对象

      e1 = new Element("name");//创建元素e1,设置内容,属性
      e1.setText("C.Y. Shen");  
      e1.setAttribute("index","1");
      root.addContent(e1); 

      e2= new Element("name");//创建元素e2,设置内容,属性
      e2.setText("a.Y. Shen");  
      e2.setAttribute("index","2");
      root.addContent(e2); 
      e2.addContent(new Comment("good"));//加一条注释
      //用简洁的形式添加元素
     root.addContent(new Element("name").addContent("D.Y.CHEN").setAttribute("index", "3"));

      //  XMLOutputter XMLOut = new XMLOutputter();  
      //  XMLOut.setIndent("  ");
      //  XMLOut.setNewlines(true);

      XMLOutputter XMLOut = new XMLOutputter(" ",true);//在元素后换行,每一层元素缩排两格

      XMLOut.setEncoding("gb2312"); 
      XMLOut.output(Doc, new FileOutputStream("test1.xml"));   
 } 
   
 public static void main(String[] args) { 
       try {           
         test1 s1 = new test1();   
         System.out.println("Now we build an XML document .....");  
         s1.BuildXMLDoc(); 
       } catch (Exception e) {  
          System.out.println(e.getMessage()); 
       }    
   }
}

输出的test1.xml文件如下:
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE employees_information SYSTEM "employees.dtd">
<employees_information>
 <name index="1">C.Y. Shen</name>
 <name index="2">
  a.Y. Shen
  <!--good-->
 </name>
 <name index="3">D.Y.CHEN</name>
</employees_information>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值