調用java的api進行xml的dom解析時候,對各種xml術語不是很瞭解,導致理解困難.進而運用不熟悉.這次將xml術語詳細解釋一下,並且加入代碼進行解釋.完整的瞭解一遍.
1先看xml文件,將此文件存在項目的src包下,命名爲:bookstore.xml
<bookstore>
<book id="1">
<name>冰與火之歌</name>
<author>喬治馬丁</author>
<year>2014</year>
<price>89</price>
</book>
<book id="2">
<name>安徒生童話</name>
<year>2004</year>
<price>77</price>
<language>English</language>
</book>
</bookstore>
2.再看java的dom解析代碼,進行詳細解釋,導入的包就不寫了
public class parseXmlOfDom{
public static void main(String[] args){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db = dbf.newDocumentBuilder();
// 傳入文件路徑,返回Document對象.也就是我們要操作的對象
Document d = db.parse("src/bookstore.xml");
// 通過元素名稱解析得到 所有子節點的集合
NodeList books = d.getElementsByTagName("book");
for(int i=0;i<books.getLength();i++){
Node book = books.item(i);
// 解析得到節點 (**不是子節點**) 的屬性的 map集合
NamedNodeMap mapOfAttr = book.getAttributes();
for(int j=0;j<mapOfAttr.getLength();j++){
//通過map集合返回單個節點
Node nodeOfAttr = mapOfAttr.item(j);
//輸出節點名稱以及屬性值
System.out.print( nodeOfAttr.getNodeName() );
System.out.println( nodeOfAttr.getNodeValue() );
}//for attrOfRoot
// 解析子節點
NodeList childsOfBook = book.getChildNodes();
for(int l=0;l<childsOfBook.getLength;l++){
//節點共有9個,偶數節點沒有內容(節點類型爲Text).從0到8.
if( l%2 != 0){
Node childOfBook = childsOfBook.item(l);
System.out.print(childOfBook.getNodeName());
//注意:閉合標籤內部被認爲是子節點.此時"冰與火之歌"是子節點的節點值
Node grandchildOfBook = childOfBook.getFirstChild();
System.out.println(grandchildOfBook.getNodeValue() );
}
}
}
}//try
catch(ParserConfigurationException e){
e.printStackTrace();
}catch(SAXException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}//main
}//class
END:
附上表格:
節點類型……..nodeName返回值 ………nodeValue返回值
Element……..element名字 ……………null
Attr…………..attr名字…………………屬性值
Text…………. #text …………………節點內容
節點內容
主要是xml屬性不熟悉以及java的方法作用不了解.邏輯上沒有什麼難度.