使用Jdom,操作xml從此變得方便,^_^

一、創(chuàng)建XML文件

Document doc = new Document(new Element("rootElement"))

或者

Document doc = new Document();
// 根元素

 Element root = new Element("persons");
 doc.addContent(root);

// add person
Element person = new Element("person").setText("test1");
root.addContent(person);

//add person 2
person = new Element("person").setText("test2");
root.addContent(person);

 

另外一種方式:

Document doc = new Document(new Element("family")
.addContent(new Element("mom"))
.addContent(new Element("dad").addContent("kidOfDad")));

二、解析XML文件

   一般而言,使用org.jdom.input.SAXBuilder更快,推薦使用,而org.jdom.input.DOMBuilder適用于已經(jīng)存在DOM對(duì)象的場(chǎng)合。

SAXBuilder b = new SAXBuilder();
            // Create the document
Document doc = b.build(new File(xmlfilename));

  • 獲取根元素:Element webapp = doc.getRootElement();
  • 獲取子節(jié)點(diǎn)(支持namespace):

// Get a List of direct children as Elements
List allChildren = element.getChildren();

// Get all direct children with a given name
List namedChildren = element.getChildren("name");

// Get the first kid with a given name
Element kid = element.getChild("name");

  • 增加/刪除子節(jié)點(diǎn),可以像操作List對(duì)象一樣操作子節(jié)點(diǎn)集合,當(dāng)然也可以以傳統(tǒng)的方式來(lái)操作

List allChildren = element.getChildren();
// Remove the fourth child
allChildren.remove(3);
// Remove all children named "jack"
allChildren.removeAll(element.getChildren("jack"));

或者
element.removeChildren("jack");
// Add a new child
allChildren.add(new Element("jane"));

或者
element.addContent(new Element("jane"));
// Add a new child in the second position
allChildren.add(1, new Element("second"));

  • 讀取/設(shè)置屬性

// 讀取屬性:

String value =table.getAttributeValue("width");// table 是element
// 也可以在讀取屬性的同時(shí)進(jìn)行類型轉(zhuǎn)換
try {
value =table.getAttribute("border").getIntValue();
}
catch (DataConversionException e) { }

// 設(shè)置屬性

// Add an attribute
table.addAttribute("vspace", "0");
// Add an attribute more formally 比較正式的寫法
table.addAttribute(new Attribute("name", "value"))
// Remove an attribute
table.removeAttribute("border");
// Remove all attributes 移除所有屬性
table.getAttributes().clear();

  • 獲取元素的內(nèi)容

比如<description>A cool demo</description>,則可以直接獲取內(nèi)容

String content = element.getText();

// 移除多余的空白,字符串前后的空白,不會(huì)移除字符串內(nèi)部的空白

element.getTextNormalize();

  • 設(shè)置元素的內(nèi)容

// This blows away all current content
element.setText("A new description");

//Special characters are interpreted correctly: 特殊字符可以被正確地轉(zhuǎn)義

element.setText("<xml> content");

// 創(chuàng)建cdata元素

element.addContent(new CDATA("<xml> content"));

三、輸出XML

XMLOutputter 類用來(lái)實(shí)現(xiàn)XML文件的輸出,在創(chuàng)建的時(shí)候需要一個(gè)Format對(duì)象來(lái)格式化XML文件,F(xiàn)ormat對(duì)象是一個(gè)工廠類,提供幾個(gè)靜態(tài)的工廠方法來(lái)提供一些常規(guī)的XML格式,比如getPrettyFormat():

XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        try {
            outputter.output(doc, new FileOutputStream(new File("xmlfile/persons.xml")));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

 

四、xml Namespace的支持

  • 獲取名空間

Namespace xhtml = Namespace.getNamespace("xhtml", “http://www.w3.org/1999/xhtml”);

  • Namespace 對(duì)象可以作為Element 和Attribute的大多數(shù)方法的可選參數(shù):

List kids = element.getChildren("p", xhtml);
Element kid = element.getChild("title", xhtml);
Attribute height = element.getAttribute("height", xhtml);

附錄:Java下XML編程接口比較:DOM SAX JDOM JAXP(網(wǎng)絡(luò)裝載)

一、DOM (文檔對(duì)象模型)
為 XML 文檔的已解析版本定義了一組接口。解析器讀入整個(gè)文檔,然后構(gòu)建一個(gè)駐留內(nèi)存的樹結(jié)構(gòu),然后代碼就可以使用 DOM 接口來(lái)操作這個(gè)樹結(jié)構(gòu)。
優(yōu)點(diǎn):整個(gè)文檔樹在內(nèi)存中,便于操作;支持刪除、修改、重新排列等多種功能;
缺點(diǎn):將整個(gè)文檔調(diào)入內(nèi)存(包括無(wú)用的節(jié)點(diǎn)),浪費(fèi)時(shí)間和空間;
使用場(chǎng)合:一旦解析了文檔還需多次訪問這些數(shù)據(jù);
硬件資源充足(內(nèi)存、CPU)
 二、SAX
為解決DOM的問題,出現(xiàn)了SAX。
SAX ,事件驅(qū)動(dòng)。當(dāng)解析器發(fā)現(xiàn)元素開始、元素結(jié)束、文本、文檔的開始或結(jié)束等時(shí),發(fā)送事件,程序員編寫響應(yīng)這些事件的代碼,保存數(shù)據(jù)。
優(yōu)點(diǎn):不用事先調(diào)入整個(gè)文檔,占用資源少;
SAX解析器代碼比DOM解析器代碼小,適于Applet,下載
缺點(diǎn):不是持久的;事件過后,若沒保存數(shù)據(jù),那么數(shù)據(jù)就丟了;
無(wú)狀態(tài)性;從事件中只能得到文本,但不知該文本屬于哪個(gè)元素;
使用場(chǎng)合:Applet;
只需XML文檔的少量?jī)?nèi)容,很少回頭訪問;
機(jī)器內(nèi)存少;
 三、JDOM
為減少DOM、SAX的編碼量,出現(xiàn)了JDOM;
優(yōu)點(diǎn):20-80原則,極大減少了代碼量
使用場(chǎng)合:要實(shí)現(xiàn)的功能簡(jiǎn)單,如解析、創(chuàng)建等,但在底層,JDOM還是使用SAX(最常用)、DOM、Xanan
四、JAXP
為多個(gè)XML解析器提供了統(tǒng)一編程接口
更換解析器,不用更改代碼
使用場(chǎng)合:若不用Jdom,一般建議使用JAPX,將代碼與各種解析器的實(shí)現(xiàn)細(xì)節(jié)隔離。