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

第3篇,尝试使用JDOM

Posted on 2006-11-24 21:10 Zou Ang 阅读(208) 评论(0)  编辑  收藏 所属分类:
今天晚上在宿舍看那本《Java Web服务高级教程》,刚开始讲的是xml,所以试着用JDOM来读了一个自己写的xml文档:
MyXml.xml
<?xml version="1.0" encoding="UTF-8"?>
<directory>
    
<file filename = "book.xml">
        
<description>A book list</description>
    
</file>
    
    
<file filename="funny.jpg">
        
<description>A funny picture</description>
    
</file>
</directory>

测试类
package learn.xml;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.xml.sax.SAXException;

/**
 * 
 * 2006-11-24
 * 
 * 
@author Zou Ang Contact <a href ="mailto:richardeee@gmail.com">Zou Ang</a>
 
*/

public class ParseXML {
    
public void testParse() throws IOException{
        SAXBuilder builder 
= new SAXBuilder(false);
//        File file = new File("D:/XWL/AjaxLearning/WebContent/WEB-INF/dwr.xml");
        try {
            Document document 
= builder.build(new File(
                    
"D:/XWL/AjaxLearning/WebContent/WEB-INF/MyXml.xml"));
            Element root 
= document.getRootElement();
            List
<Element> children = root.getChildren();
            System.out.println(
"Number of childern: " + children.size());
            
for(Element el : children){
                String str 
= el.getChildText("description");
                System.out.println(str);
            }

        }
 catch (JDOMException e) {
            e.printStackTrace();
        }

    }

    
    
public void createXML()throws IOException,JDOMException{
//        SAXBuilder builder = new SAXBuilder(false);
        Element root = new Element("MyMessage");
        Document document 
= new Document(root);
        Element message 
= new Element("message");
        message.setAttribute(
"type""text");
        message.setContent(
new Element("content").addContent("First Message"));
        root.addContent(message);
        XMLOutputter outputter 
= new XMLOutputter(Format.getPrettyFormat());
        outputter.output(document, System.out);
//        root.
    }

    
public static void main(String arg[]) throws IOException,JDOMException{
        ParseXML pxml 
= new ParseXML();
        pxml.testParse();
        pxml.createXML();
    }

}


输出:
Number of childern:  2
A book list
A funny picture

<? xml version = " 1.0 "  encoding = " UTF-8 " ?>
< MyMessage >
  
< message type = " text " >
    
< content > First Message </ content >
  
</ message >
</ MyMessage >

要尽快熟练使用JDOM才行

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


网站导航: