XML文檔解析(寫入、修改XML文件)

文檔對象模型DOM

文檔對象模型(通常稱爲DOM)爲XML文檔的已解析版本定義了一組接口。解析器讀入整個文檔,然後構建一個駐留內存的樹結構,然後就可以使用DOM接口來操作這個樹結構。

  • 可以遍歷樹以瞭解原始文檔包含了什麼
  • 可以刪除樹的幾個部分
  • 可以重新排列樹和添加新的分支

DOM解析

DOM構建整個文檔駐留內存的樹。如果文檔很大,就會要求有極大的內存。

DOM創建表示原始文檔中每個東西的對象,包括元素、文本、屬性和空格。如果只關注原始文檔的一小部分,那麼創建那些永遠不被使用的對象是極其浪費的。

DOM解析器必須在代碼取得控制權之前讀取整個文檔。對於非常大的文檔,這會引起顯著的延遲
這些僅僅是由文檔對象模型的設計引起的問題;撇開這些問題,DOM API是解析XML文檔非常有用的方法。

JDOM技術

JDOM提供了以DOM思想操作XML數據文件的方式,但和標準的DOM接口並不兼容。但由於其簡單性,在java開發領域有着廣泛的應用。

JDOM是爲java優化的。
JDOM試圖組合DOM和SAX的優點。它被設計成一個可以在小內存上快速執行輕量級api。
操作:

  1. 如何用JDOM創建一個XML文檔
  2. 如何解析已有XML文檔
  3. 如何修改已有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 ();
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章