JDOM 操作xml文件方法

import  java.io.IOException;
import  java.util.HashMap;
import  java.util.Map;
import  org.jdom.Attribute;
import  org.jdom.DocType;
import  org.jdom.Document;
import  org.jdom.Element;
import  org.jdom.ProcessingInstruction;
import  org.jdom.output.Format;
import  org.jdom.output.XMLOutputter;
public   class  ProduceXMl  {
 
 
 
public static void main(String[] args) throws IOException {
  
  Document doc 
= new Document(); //创建空白文档

  
/*

   * 创建PI并添加到文档
   
*/

  Map map 
= new HashMap();
  map.put(
"type","text/xsl");
  map.put(
"href","products.xsl");
  ProcessingInstruction pi 
= new ProcessingInstruction("xml-stylesheet",map);//处理指令 
  
//将处理指令添加
  doc.addContent(pi);
  
        
/*
         * 创建文档类型并添加到文档
         
*/

  DocType  type  
= new DocType("productsDetails"); //文档类型
  type.setPublicID("public.dtd");    //设为 public
  
//type.setSystemID("system.dtd");   //设为 system
  
//添加文档类型
  doc.addContent(type);
  
  Element root 
= new Element("productsDetails"); //创建一个元素
  doc.setRootElement(root); //将该元素做为根元素

/*

加入注释

*/


root .addContent(
new Comment("good"));//加一条注释

/*

加入复杂文本

*/


   CDATA data
=new CDATA("dfasfdasfdasd<adafa></adfasfsa>>SDFSAFASFDSAfa0");

root .addContent(data);

  Element product 
= new Element("product");
  root.addContent(product); 
//将product做为productsDetails的子元素
  
  Attribute  att 
= new Attribute("productID","0001"); //创建属性
  product.setAttribute(att); //为product设置属性
  
  
//为product创建子元素,并将其content分别设为100.00,red
  product.addContent(new Element("rate").setText("100.00"));
  product.addContent(
new Element("color").setText("红色"));
  
  
/*
   * 格式化输出
   
*/

  XMLOutputter outp 
= new XMLOutputter();//用于输出jdom 文档
  Format format=Format.getPrettyFormat(); //格式化文档
  format.setEncoding("GBK"); //由于默认的编码是utf-8,中文将显示为乱码,所以设为gbk
  outp.setFormat(format);
  outp.output(doc,System.out); 
//输出文档
  
 }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值