dom4j解析
(1) dom4j
//建立解析器
saxreader saxreader = newsaxreader();
//通過解析器的read方法將xml檔案 讀取到document物件
document doc =saxreader.read("要讀取的.xml");
//獲取xml檔案的根節點:students
element root = doc.getrootelement();
//開始遍歷根節點students
for(iteratoriter =root.elementiterator(); iter.hasnext();)
@override
publicvoid characters(char ch, int start, int length)throwssaxexception
@override
publicvoid endelement(string uri, string localname, string qname)
throwssaxexception
}這是我的xml檔案,對比的看更好理解
<?xmlversion="1.0" encoding="utf-8"?>
zhangsan 20
wangwu 29
xpath
//獲取解析工廠
documentbuilde***ctorybuilde***ctory = documentbuilde***ctory.newinstance();
//獲取解析器
documentbuilder builder =builde***ctory.newdocumentbuilder();
//通過解析器的parser方法將xml檔案讀取到document(org.w3c.document)物件中
document doc =builder.parse("books.xml");
//獲取xpath物件
xpath xpath =xpathfactory.newinstance().newxpath();
//獲取bookstore節點下book屬性,category值為web下的第二個title節點的文字內容
//bookstore -> book[@categor='web'][2] -> title ->text()
string titlexpath ="/bookstore/book[@category='web'][2]/title/text()";
string title = (string)xpath.evaluate(titlexpath,doc,xpathconstants.string);
system.out.println(title);
//獲取bookstore節點下book屬性 category 值為 web 的title 屬性的uk 節點內容
//bookstore- > book[@category='web'] -> title[@lang='uk']
string uktitlexpath ="/bookstore/book[@category='web']/title[@lang='uk']/text()";
string uktitle= (string)xpath.evaluate(uktitlexpath,doc,xpathconstants.string);
system.out.println(uktitle);
//獲取bookstore下的 book 屬性 category 值為 cooking 的 title 的 lang 屬性的值
//bookstore->book[category='cooking']-> title -> @lang
string langxpath="/bookstore/book[@category='cooking']/title/@lang";
string langvalue = (string)xpath.evaluate(langxpath,doc,xpathconstants.string);
system.out.println(langvalue);
//獲取bookstore節點下的所有book
//bookstore-> book
nodelist books = (nodelist)xpath.evaluate("/bookstore/book",doc,xpathconstants.nodeset);
//開始遍歷books
for(inti=0;i//獲取到book節點
nodebook = books.item(i);
stringinnertitle = (string)xpath.evaluate("title/text()",book,xpathconstants.string);
system.out.println(innertitle);
stringauthor = (string)xpath.evaluate("author/text()",book,xpathconstants.string);
system.out.println(author);
這是我的xml檔案,對比的看更好理解
<?xmlversion="1.0" encoding="utf-8"?>
harry potter
jk. rowling
2005
29.99
everyday italian
giadade laurentiis
2005
30.00
learning xml
erikt. ray
2003
39.95
xquery kick start
jamesmcgovern
2003
49.99
XML的四種解析方式
測 試 這種處理的優點非常類似於流 的優點。分析能夠立即開始,而不是等待所有的資料被處理。而且,由於應用程式只是在讀取資料時檢查資料,因此不需要將資料儲存在記憶體中。這對於大型文件來說是個巨大的優點。事實上,應用程式甚至不必解析整個文件 它可以在某個條件得到滿足時停止解析。一般來說,sax 還比它的...
四種xml的解析方式
比較 1.dom4j效能最好,連sun的jaxm也在用dom4j。目前許多開源專案中大量採用dom4j,例如大名鼎鼎的hibernate也用dom4j來讀取xml配置檔案。如果不考慮可移植性,那就採用dom4j.2.jdom和dom在效能測試時表現不佳,在測試10m文件時記憶體溢位,但可移植。在小文...
Android xml的3種解析方式
1.dom 原理 就是把整個文件載入到記憶體 生成乙個樹狀結構 dom tree 優點 可以修改文件 缺點 比較占用記憶體 test public void domparsetest throws exception 通過dom修改文件 public void dommodifytest throw...