java DOM 解析

    xiaoxiao2021-03-25  95

      调用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的方法作用不了解.逻辑上没有什么难度.

    转载请注明原文地址: https://ju.6miu.com/read-20517.html

    最新回复(0)