DOM解析

DOM解析是xml文件解析的一种,它是一次性加载文件的所有内容,属于文档驱动的解析。具体实现如下

package com.example.parse;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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

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

import com.example.bean.Books;

public class DOMParse implements IParse {

    private List<Books> l;

    @Override
    public List<Books> parse(InputStream is) {
        l = new ArrayList<Books>();
        try {
            // 得到工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 创建DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();
            // Document对象
            Document parse = builder.parse(is);
            // 得到根节点
            Element element = parse.getDocumentElement();
            // 通过根节点获得所有的图书
            NodeList list = element.getElementsByTagName("book");
            for (int i = 0; i < list.getLength(); i++) {
                Books books = new Books();
                // 获得单个book节点
                Node node = list.item(i);
                // 获得book节点下的子节点
                NodeList childNodes = node.getChildNodes();
                for (int j = 0; j < childNodes.getLength(); j++) {
                    // 获得单个节点
                    Node node2 = childNodes.item(j);
                    // 取得子节点的名称
                    String nodeName = node2.getNodeName();
                    // 判断取得子节点的名称
                    if ("name".equalsIgnoreCase(nodeName)) {
                        // 如果子节点的名称是所需要的那么就得到节点的值
                        String name = node2.getFirstChild().getNodeValue();
                        books.setName(name);
                    } else if ("author".equalsIgnoreCase(nodeName)) {
                        // 如果子节点的名称是所需要的那么就得到节点的值
                        String author = node2.getFirstChild().getNodeValue();
                        books.setAuthor(author);
                    } else if ("price".equalsIgnoreCase(nodeName)) {
                        // 如果子节点的名称是所需要的那么就得到节点的值
                        String price = node2.getFirstChild().getNodeValue();
                        books.setPrice(price);
                    }
                }
                l.add(books);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return l;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值