DOM读取XML文件

创建XML文件:

<?xml version="1.0" encoding="utf-8"?>
<bookstore>
    <!--记录书本的信息 -->
    <book Type="必修课">
        <title>数据结构</title>
        <author>张三</author>
        <price>30.00</price>
    </book>
    <book Type="必修课" >
        <title>java基础</title>
        <author>李四</author>
        <price>40.00</price>
    </book>
    <book Type="必修课" >
        <title>计算机组成原理</title>
        <author>王五</author>
        <price>50.00</price>
    </book>
    <book Type="必修课">
        <title>软件质量保证与管理</title>
        <author>赵六</author>
        <price>60.00</price>
    </book>
    <book Type="必修课" >
        <title>算法设计与分析</title>
        <author>李七</author>
        <price>70.00</price>
    </book>
</bookstore>

工厂模式进行XML解析:

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;


public class DOMReadXML {

    public static void main(String[] args) {


        try{

            File file = new File("XmlDemo.xml");

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            DocumentBuilder builder = factory.newDocumentBuilder();

            Document doc = builder.parse(file);

            NodeList nl = doc.getElementsByTagName("book");

            for(int i=0; i<nl.getLength();i++){

                System.out.print("书名:"+ doc.getElementsByTagName("title").item(i).getFirstChild().getNodeValue()); 
                System.out.println("作者:"+ doc.getElementsByTagName("author").item(i).getFirstChild().getNodeValue()); 
                System.out.println("价格:"+ doc.getElementsByTagName("price").item(i).getFirstChild().getNodeValue()); 
            }




        }catch (Exception e) { 
            e.printStackTrace(); 
        }
    }
}

运行结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值