使用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對象的場合。
SAXBuilder b = new SAXBuilder();
// Create the document
Document doc = b.build(new File(xmlfilename));
- 獲取根元素:Element webapp = doc.getRootElement();
- 獲取子節(jié)點(支持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é)點,可以像操作List對象一樣操作子節(jié)點集合,當然也可以以傳統(tǒng)的方式來操作
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"));
- 讀取/設置屬性
// 讀取屬性:
String value =table.getAttributeValue("width");// table 是element
// 也可以在讀取屬性的同時進行類型轉換
try {
value =table.getAttribute("border").getIntValue();
}
catch (DataConversionException e) { }
// 設置屬性
// 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();
// 移除多余的空白,字符串前后的空白,不會移除字符串內(nèi)部的空白
element.getTextNormalize();
- 設置元素的內(nèi)容
// This blows away all current content
element.setText("A new description");
//Special characters are interpreted correctly: 特殊字符可以被正確地轉義
element.setText("<xml> content");
// 創(chuàng)建cdata元素
element.addContent(new CDATA("<xml> content"));
三、輸出XML
XMLOutputter 類用來實現(xiàn)XML文件的輸出,在創(chuàng)建的時候需要一個Format對象來格式化XML文件,F(xiàn)ormat對象是一個工廠類,提供幾個靜態(tà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 對象可以作為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)絡裝載)
一、DOM (文檔對象模型)
為 XML 文檔的已解析版本定義了一組接口。解析器讀入整個文檔,然后構建一個駐留內(nèi)存的樹結構,然后代碼就可以使用 DOM 接口來操作這個樹結構。
優(yōu)點:整個文檔樹在內(nèi)存中,便于操作;支持刪除、修改、重新排列等多種功能;
缺點:將整個文檔調(diào)入內(nèi)存(包括無用的節(jié)點),浪費時間和空間;
使用場合:一旦解析了文檔還需多次訪問這些數(shù)據(jù);
硬件資源充足(內(nèi)存、CPU)
二、SAX
為解決DOM的問題,出現(xiàn)了SAX。
SAX ,事件驅動。當解析器發(fā)現(xiàn)元素開始、元素結束、文本、文檔的開始或結束等時,發(fā)送事件,程序員編寫響應這些事件的代碼,保存數(shù)據(jù)。
優(yōu)點:不用事先調(diào)入整個文檔,占用資源少;
SAX解析器代碼比DOM解析器代碼小,適于Applet,下載
缺點:不是持久的;事件過后,若沒保存數(shù)據(jù),那么數(shù)據(jù)就丟了;
無狀態(tài)性;從事件中只能得到文本,但不知該文本屬于哪個元素;
使用場合:Applet;
只需XML文檔的少量內(nèi)容,很少回頭訪問;
機器內(nèi)存少;
三、JDOM
為減少DOM、SAX的編碼量,出現(xiàn)了JDOM;
優(yōu)點:20-80原則,極大減少了代碼量
使用場合:要實現(xiàn)的功能簡單,如解析、創(chuàng)建等,但在底層,JDOM還是使用SAX(最常用)、DOM、Xanan
四、JAXP
為多個XML解析器提供了統(tǒng)一編程接口
更換解析器,不用更改代碼
使用場合:若不用Jdom,一般建議使用JAPX,將代碼與各種解析器的實現(xiàn)細節(jié)隔離。