加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML解析之DOM解析

发布时间:2020-12-16 05:53:16 所属栏目:百科 来源:网络整理
导读:XML解析方式有两种,分别是DOM解析与SAX解析。 DOM解析是根据XML文档的结构,将整个XML文档加载进入内存中,按文档结构的顺序来解析XML。DOM操作也能对XML文档数据进行操作。 DOM解析可以随机访问XML某节点的数据,但缺点是如果xml文件比较大,或者结构比较
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读