XML--Java中的四种常见解析方式--dom

Java中常用的解析方式主要有四种:

Java 自带:Dom、Sax。

外加包:Jdom、Dom4j。

1.Dom

主要的构建方式

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

DocumentBuilder db=dbf.newDocumentBuilder();

Document dm=db.parse("rec\\books.xml");

其中节点类为Node  节点集合类为NodeList 

attr属性集合用NamedNodeMap 通过getAttributes()实现。

NodeList booklist=dm.getElementsByTagName("book");

NodeList childnodes = book.getChildNodes();

 

字节点childnodes集合用getChildNodes()实现

字节点第i个通过childnodes.item(i)获得

“集合”长度用get.length()实现

节点类型有多种 通过Node.ELEMENT_NODE可以获得该节点的类型

如上图如要获得<name>数据结构</name>中的文本

则需要通过childnodes.item(k).getTextContent()直接获得文本

或者通过childnodes.item(k).getFirstchild().getNodeName。(文本被视为name标签的Text类型子节点)

PS:xml空格会被视为一个text类型的节点。

例子:

public class Xmltest {
    public List<book> books;
    public Xmltest(){
        this.books=new ArrayList();
    }
    public static void main(String[] args) throws Exception {
        Xmltest test=new Xmltest();
        int i=2005;
        int j=i>>2;
        System.out.println(j);
        test.Jiexi();
        test.foreprint();
}
    public void Jiexi() throws Exception{
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        DocumentBuilder db=dbf.newDocumentBuilder();
        Document dm=db.parse("E:\\books.xml");// TODO Auto-generated method stub
        NodeList booklist=dm.getElementsByTagName("book");
        for (int i = 0; i < booklist.getLength(); i++) {
            book temp=new book();
            Node book = booklist.item(i);
            NamedNodeMap attrs = book.getAttributes();
            NodeList childnodes = book.getChildNodes();
            for (int k = 0; k < childnodes.getLength(); k++) {
                if (childnodes.item(k).getNodeType() == Node.ELEMENT_NODE) {
                    if (childnodes.item(k).getNodeName() == "name")
                        temp.name = childnodes.item(k).getn;
                    if (childnodes.item(k).getNodeName() == "years")
                        temp.years = childnodes.item(k).getTextContent();
                    if (childnodes.item(k).getNodeName() == "price")
                        temp.price = childnodes.item(k).getTextContent();
                }
            }    
            books.add(temp);
        }

    }
    public void foreprint(){
        for(book temp:books){
            System.out.println("------------");
            System.out.println("书名为:"+temp.name);
            System.out.println("出版年份:"+temp.years);
            System.out.println("价格为:"+temp.price+"元");
            
        }
    }
    }
View Code

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值