今天晚上在宿舍看那本《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才行
MyXml.xml










測試類











































































輸出:









要盡快熟練使用JDOM才行