无线&移动互联网技术研发

换位思考·····
posts - 19, comments - 53, trackbacks - 0, articles - 283
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

jdom 修改 xml

Posted on 2009-07-29 23:37 Gavin.lee 阅读(209) 评论(0)  编辑  收藏 所属分类: xml doc 操作
修改前:
<?xml version="1.0" encoding="GBK"?> 
<bookList> 
   
<book> 
       
<name>Java</name> 
       
<author>张三</author> 
       
<publishDate>2002-6-6</publishDate> 
       
<price>35.0</price> 
   
</book> 
   
<book> 
       
<name>XML</name> 
       
<author>李四</author> 
       
<publishDate>2002-9-16</publishDate> 
       
<price>92.0</price> 
   
</book> 
</bookList>
修改后:
<?xml version="1.0" encoding="UTF-8"?>
<bookList> 
   
<book hot="true"> 
       
<name>Java</name> 
       
<author>redtroy</author> 
       
<publishDate>2002-6-6</publishDate> 
       
<price>100.0</price> 
   
</book> 
   
<book> 
       
<name>XML</name> 
       
<author>李四</author> 
       
<publishDate>2002-9-16</publishDate> 
       
<price>92.0</price> 
   
</book> 
</bookList>

操作类:
package com.Gavin.xml;

import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
import java.io.*;
import java.util.List;

public class JDOMDemo {

    
public static void main(String[] args) throws Exception {
        SAXBuilder sb 
= new SAXBuilder();
        Document doc 
= sb.build(new FileInputStream("d:/exampleA.xml"));
        Element root 
= doc.getRootElement();
        List books 
= root.getChildren();
        Element book 
= (Element) books.get(0);
        Attribute newattribute 
= new Attribute("hot""true");
        book.setAttribute(newattribute);
        Element author 
= (Element) book.getChild("author");
        author.setText(
"redtroy");
        Element price 
= book.getChild("price");
        price.setText(Float.toString(
100));

        Format format 
= Format.getCompactFormat();
        
//设置文档字符编码
        format.setEncoding("GB18030");
        
//设置缩进字符串
        format.setIndent("  ");

//        XMLOutputter out = new XMLOutputter();
        XMLOutputter out = new XMLOutputter(format);
        out.output(doc, 
new FileOutputStream("d:/exampleB.xml"));
    }

}

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


网站导航: