文檔對象模型DOM
文檔對象模型(通常稱為DOM)為XML文檔的已解析版本定義了一組接口。解析器讀入整個文檔,然後建構一個駐留記憶體的樹結構,然後就可以使用DOM接口來操作這個樹結構。
- 可以周遊樹以了解原始文檔包含了什麼
- 可以删除樹的幾個部分
- 可以重新排列樹和添加新的分支
DOM解析
DOM建構整個文檔駐留記憶體的樹。如果文檔很大,就會要求有極大的記憶體。
DOM建立表示原始文檔中每個東西的對象,包括元素、文本、屬性和空格。如果隻關注原始文檔的一小部分,那麼建立那些永遠不被使用的對象是極其浪費的。
DOM解析器必須在代碼取得控制權之前讀取整個文檔。對于非常大的文檔,這會引起顯著的延遲
這些僅僅是由文檔對象模型的設計引起的問題;撇開這些問題,DOM API是解析XML文檔非常有用的方法。
JDOM技術
JDOM提供了以DOM思想操作XML資料檔案的方式,但和标準的DOM接口并不相容。但由于其簡單性,在java開發領域有着廣泛的應用。
JDOM是為java優化的。
JDOM試圖組合DOM和SAX的優點。它被設計成一個可以在小記憶體上快速執行輕量級api。
操作:
- 如何用JDOM建立一個XML文檔
- 如何解析已有XML文檔
- 如何修改已有XML文檔
寫入XML:
public class Test {
private void createXml() throws FileNotFoundException, IOException {
Element root = new Element ("resume") ;
Element name = new Element ("name") ;
Element job = new Element ("job") ;
Attribute attr = new Attribute ("startAge", "20");
name.setAttribute(attr);
name.addContent("朱元璋");
job.setText("皇帝");
root.addContent(name);
root.addContent(job);
Document doc = new Document(root) ;
//Format f = Format.getCompactFormat() ;
Format f = Format.getPrettyFormat() ;
f. setEncoding ("gbk");
XMLOutputter xmlOut = new XMLOutputter (f) ;
xmlOut.output (doc, new FileOutputStream("d:/2.xml")) ;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
new Test().createXml();
}
}
修改XML
public class Update {
private void testUpdateXml () throws JDOMException, FileNotFoundException, IOException {
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(new FileInputStream("d:/2.xml"));
Element root = doc.getRootElement();
XPath xpath = XPath.newInstance ("/resume/*");
Element e=root.getChild("name");
e.setText("zhuyuanzhang");
//Format f = Format.getCompactFormat() ;
Format f = Format.getPrettyFormat() ;
f. setEncoding ("gbk");
XMLOutputter xmlOut = new XMLOutputter (f) ;
xmlOut.output (doc, new FileOutputStream("d:/2.xml")) ;
}
public static void main(String[] args) throws FileNotFoundException, JDOMException, IOException {
new Update().testUpdateXml ();
}
}