jdom的使用

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
(1)使用JDOM首先要指定使用什麼解析器。如:
SAXBuilder builder=new SAXBuilder(false); 這表示使用的是默認的解析器
(2)得到Document,我們以後要進行的所有操作都是對這個Document操作的:
Document doc=builder.build(xmlpath);
(3)得到根元素:
Element books=doc.getRootElement();
在JDOM中所有的節點(DOM中的概念)都是一個org.jdom.Element類,當然他的子節點也是一個org.jdom.Element類。
(4)得到元素(節點)的集合:
List booklist=books.getChildren("book");
這表示得到“books”元素的所在名稱爲“book”的元素,並把這些元素都放到一個List集合中
(5)輪循List集合
for (Iterator iter = booklist.iterator(); iter.hasNext();) {
Element book = (Element) iter.next();

還有一種輪循方法是:
for(int i=0;I<booklist.size();I++){
Element book=(Element)booklist.get(i);
}
(6)取得元素的屬性:
String email=book.getAttributeValue("email");
取得元素book的屬性名爲“email”的屬性值。
(7)取得元素的子元素(爲最低層元素)的值:
String name=book.getChildTextTrim("name");
注意的是,必須確定book元素的名爲“name”的子元素只有一個。
(8)改變元素(爲最低層元素)的值:
book.getChild("name").setText("alterrjzjh");
這只是對Document的修改,並沒有在實際的XML文檔中進行修改
(9)保存Document的修改到XML文件中:
XMLOutputter outputter=new XMLOutputter();
outputter.output(doc,new FileOutputStream(xmlpath));

我們先要有一個XMLOutputter類,再把已經修改了的Document保存進XML文檔中。
到此。用JDOM解析和處理XML文檔講解完了,麻雀雖小,五臟俱全。現在已對JDOM有個整體上的概念了吧
JDOM包概述(轉)
2009-10-01 21:02

二、JDOM 包概覽
JDOM是由以下幾個包組成的
org.JDOM
org.JDOM.input
org.JDOM.output
org.JDOM.adapters
org.JDOM.transform 
三、JDOM 類說明

org.JDOM
這個包裏的類是你解析xml文件後所要用到的所有數據類型。
Attribute
CDATA
Coment
DocType
Document
Element
EntityRef
Namespace
ProscessingInstruction
Text

org.JDOM.transform
在涉及xslt格式轉換時應使用下面的2個類
JDOMSource
JDOMResult

org.JDOM.input
輸入類,一般用於文檔的創建工作
SAXBuilder
DOMBuilder
ResultSetBuilder

org.JDOM.output
輸出類,用於文檔轉換輸出
XMLOutputter
SAXOutputter
DomOutputter
JTreeOutputter

使用前注意事項:
1.JDOM對於JAXP 以及 TRax 的支持
JDOM 支持JAXP1.1:你可以在程序中使用任何的parser工具類,默認情況下是JAXP的parser。
制定特別的parser可用如下形式
SAXBuilder parser 
= new SAXBuilder("org.apache.crimson.parser.XMLReaderImpl");
Document doc = parser.build("http://www.cafeconleche.org/");
// work with the document...
JDOM也支持TRaX:XSLT可通過JDOMSource以及JDOMResult類來轉換(參見以後章節)
2.注意在JDOM裏文檔(Document)類由org.JDOM.Document 來表示。這要與org.w3c.dom中的Document區別開,這2種格式如何轉換在後面會說明。
以下如無特指均指JDOM裏的Document。


四、JDOM主要使用方法
1.Ducument類
(1)Document的操作方法:
Element root = new Element("GREETING");
Document doc = new Document(root);
root.setText("Hello JDOM!");
或者簡單的使用Document doc = new Document(new Element("GREETING").setText("Hello JDOM!t"));

這點和DOM不同。Dom則需要更爲複雜的代碼,如下:
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder =factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root =doc.createElement("root");
Text text = doc.createText("This is the root");
root.appendChild(text);
doc.appendChild(root);


注意事項:JDOM不允許同一個節點同時被2個或多個文檔相關聯,要在第2個文檔中使用原來老文檔中的節點的話。首先需要使用detach()把這個節點分開來。

(2)從文件、流、系統ID、URL得到Document對象:
DOMBuilder builder = new DOMBuilder();
Document doc = builder.build(new File("jdom_test.xml"));

SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(url);
在新版本中DOMBuilder 已經Deprecated掉 DOMBuilder.builder(url),用SAX效率會比較快。

這裏舉一個小例子,爲了簡單起見,使用String對象直接作爲xml數據源:

public jdomTest() {
String textXml = null;
textXml = "<note>";
textXml = textXml +
"<to>aaa</to><from>bbb</from><heading>ccc</heading><body>ddd</body>";
textXml = textXml + "</note>";
SAXBuilder builder = new SAXBuilder();
Document doc = null;
Reader in= new StringReader(textXml);
try {
doc = builder.build(in);
Element root = doc.getRootElement();
List ls = root.getChildren();//注意此處取出的是root節點下面的一層的Element集合
for (Iterator iter = ls.iterator(); iter.hasNext(); ) {
Element el = (Element) iter.next();
if(el.getName().equals("to")){
System.out.println(el.getText());
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
catch (JDOMException ex) {
ex.printStackTrace();
}
}

很簡單把。


(3)DOM的document和JDOM的Document之間的相互轉換使用方法,簡單!
DOMBuilder builder = new DOMBuilder();
org.jdom.Document jdomDocument = builder.build(domDocument);
// work with the JDOM document…

DOMOutputter converter = new DOMOutputter();
org.w3c.dom.Document domDocument = converter.output(jdomDocument);
// work with the DOM document…

2.XML文檔輸出
XMLOutPutter類:
JDOM的輸出非常靈活,支持很多種io格式以及風格的輸出
Document doc = new Document(...);
XMLOutputter outp = new XMLOutputter();
// Raw output
outp.output(doc, fileOutputStream);
// Compressed output
outp.setTextTrim(true);
outp.output(doc, socket.getOutputStream());
// Pretty output
outp.setIndent(" ");
outp.setNewlines(true);
outp.output(doc, System.out);
......
詳細請參閱最新的JDOM API手冊


3.Element 類:
(1)瀏覽Element樹
//獲得根元素element
Element root = doc.getRootElement();
// 獲得所有子元素的一個list
List allChildren = root.getChildren();
// 獲得指定名稱子元素的list
List namedChildren = root.getChildren("name");
//獲得指定名稱的第一個子元素
Element child = root.getChild("name");
(這裏的List是java.util.List)

JDOM給了我們很多很靈活的使用方法來管理子元素
List allChildren = root.getChildren();
// 刪除第四個子元素
allChildren.remove(3);
// 刪除叫“jack”的子元素
allChildren.removeAll(root.getChildren("jack"));

root.removeChildren("jack"); // 便捷寫法
// 加入
allChildren.add(new Element("jane"));

root.addContent(new Element("jane")); // 便捷寫法
allChildren.add(0, new Element("first"));


(2)移動Elements:
在JDOM裏很簡單
Element movable = new Element("movable");
parent1.addContent(movable); // place
parent1.removeContent(movable); // remove
parent2.addContent(movable); // add

在Dom裏
Element movable = doc1.createElement("movable");
parent1.appendChild(movable); // place
parent1.removeChild(movable); // remove
parent2.appendChild(movable); // 出錯!

補充:
糾錯性
JDOM的Element構造函數(以及它的其他函數)會檢查element是否合法。
而它的add/remove方法會檢查樹結構,檢查內容如下:
1.在任何樹中是否有迴環節點
2.是否只有一個根節點
3.是否有一致的命名空間(Namespaces)

(3)Element的text內容讀取
<description>
A cool demo
</description>

// The text is directly available
// Returns "/n A cool demo/n"
String desc = element.getText();

// There's a convenient shortcut
// Returns "A cool demo"
String desc = element.getTextTrim();

(4)Elment內容修改
element.setText("A new description");
3.可正確解釋特殊字符
element.setText("<xml> content");
4.CDATA的數據寫入、讀出
element.addContent(new CDATA("<xml> content"));
String noDifference = element.getText();

混合內容
element可能包含很多種內容,比如說

<table>
<!-- Some comment -->
Some text
<tr>Some child element</tr>
</table>

取table的子元素tr
String text = table.getTextTrim();
Element tr = table.getChild("tr");

也可使用另外一個比較簡單的方法
List mixedCo = table.getContent();
Iterator itr = mixedCo.iterator();
while (itr.hasNext()) {
Object o = i.next();
if (o instanceof Comment) {
...
}
// 這裏可以寫成Comment, Element, Text, CDATA,ProcessingInstruction, 或者是EntityRef的類型
}
// 現在移除Comment,注意這裏遊標應爲1。這是由於回車鍵也被解析成Text類的緣故,所以Comment項應爲1。
mixedCo.remove(1);

4.Attribute類
<table width="100%" border="0"> </table>
//獲得attribute
String width = table.getAttributeValue("width");
int border = table.getAttribute("width").getIntValue();
//設置attribute
table.setAttribute("vspace", "0");
// 刪除一個或全部attribute
table.removeAttribute("vspace");
table.getAttributes().clear();

5.處理指令(Processing Instructions)操作
一個Pls的例子
<?br?>
<?cocoon-process type="xslt"?>
| |
| |
目標 數據

處理目標名稱(Target)
String target = pi.getTarget();
獲得所有數據(data),在目標(target)以後的所有數據都會被返回。
String data = pi.getData();
獲得指定屬性的數據
String type = pi.getValue("type");
獲得所有屬性的名稱
List ls = pi.getNames();

6.命名空間操作
<xhtml:html 
xmlns:xhtml="http://www.w3.org/1999/xhtml">
<xhtml:title>Home Page</xhtml:title>
</xhtml:html>

Namespace xhtml = Namespace.getNamespace("xhtml", "http://www.w3.org/1999/xhtml");
List kids = html.getChildren("title", xhtml);
Element kid = html.getChild("title", xhtml);
kid.addContent(new Element("table", xhtml));

7.XSLT格式轉換
使用以下函數可對XSLT轉換
最後如果你需要使用w3c的Document則需要轉換一下。
public static Document transform(String stylesheet,Document in)
throws JDOMException {
try {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(new StreamSource(stylesheet));
JDOMResult out = new JDOMResult();
transformer.transform(new JDOMSource(in), out);
return out.getDeocument();
}
catch (TransformerException e) {
throw new JDOMException("XSLT Trandformation failed", e);
}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章