XML解析之DOM解析
来源:互联网 发布:淘宝哪个类目好做 编辑:程序博客网 时间:2024/05/22 09:44
XML解析方式有两种,分别是DOM解析与SAX解析。
DOM解析是根据XML文档的结构,将整个XML文档加载进入内存中,按文档结构的顺序来解析XML。DOM操作也能对XML文档数据进行操作。
DOM解析可以随机访问XML某节点的数据,但缺点是如果xml文件比较大,或者结构比较复杂时,对内存的要求会比较高。
下面对bookstore.xml进行解析,xml结构如下
<pre name="code" class="html"><?xml version="1.0" encoding="ISO-8859-1"?><bookstore><book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price></book><book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book><book category="web"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book><book category="web"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book></bookstore>
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {/*使用dom解析xml步骤: * 1、建立DocumentBuilderFactory * 2、建立DocumentBuilder * 3、建立Document * 4、建立NodeList * 5、进行XML信息读取 */DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();Document doc = builder.parse("D:"+File.separator+"Books_XML.xml");NodeList nl = doc.getElementsByTagName("book");String title ,author,year,price;for(int i=0;i<nl.getLength();i++){NodeList titlenl = doc.getElementsByTagName("title");NodeList authornl = doc.getElementsByTagName("author");NodeList yearnl = doc.getElementsByTagName("year");NodeList pricenl = doc.getElementsByTagName("price");title = titlenl.item(i).getFirstChild().getNodeValue();author = authornl.item(i).getFirstChild().getNodeValue(); year = yearnl.item(i).getFirstChild().getNodeValue(); price = pricenl.item(i).getFirstChild().getNodeValue(); System.out.println("书名:"+title+" 作者:"+author+" 日期:"+year+" 价格:"+price);}}
书名:Harry Potter 作者:J K. Rowling 日期:2005 价格:29.99书名:Everyday Italian 作者:Giada De Laurentiis 日期:2005 价格:30.00书名:Learning XML 作者:Erik T. Ray 日期:2003 价格:39.95书名:XQuery Kick Start 作者:James McGovern 日期:2003 价格:49.99
0 0
- XML解析之DOM解析
- XML解析之DOM解析
- xml解析之----DOM解析
- XML解析之DOM解析
- XML解析之DOM解析
- XML解析之DOM解析
- XML解析之DOM解析
- XML解析之DOM解析
- XML解析之DOM解析
- XML解析之DOM解析
- XML解析之DOM解析
- XML解析之DOM解析
- xml解析之dom解析
- 解析xml之--DOM
- xml解析之Dom
- XML解析之 DOM
- XML解析之Dom
- XML解析之DOM
- org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException
- MySQL计算字段
- BootLoader时钟
- 我的开源项目工作进展(1)
- mysql数据备份与还原纷
- XML解析之DOM解析
- POJ 1458 Common Subsequence 最长公共子序列
- 一款验证浮点DSP-TMS320F28335的Demo板——外设选择(2)
- FPGA机器学习之stanford机器学习第十四堂
- Apache java项目全介绍
- ip问题
- DOM 范围折叠要注意的几点
- Hadoop - YARN 启动流程
- FPGA研发之道(10)架构设计漫谈(五)数字电路的灵魂-流水线