dom解析xml文件

 package com.yangrs;

import java.io.IOException;

import javax.xml.parsers.*;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

/**
 *
 * @author spirit_fly dom解析xml
 *
 */
public class DomTest {

    public static void main(String[] args) {

        try {
            javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            org.w3c.dom.Document dom = db.parse("myxml1.xml");
            System.out.println("文件路径:" + dom.getDocumentURI());

            org.w3c.dom.Element root = dom.getDocumentElement();

            Iterator(root);    //循环迭代

            // for(int i = 0; i < nodelist.getLength(); i++) {
            // System.out.println(nodelist.item(i).getNodeName());
            // System.out.println(nodelist.item(i).getNodeValue());
            // System.out.println(nodelist.item(i).getTextContent());//这里才取得了每个结点的值
            //                
            // //会有七个节点,because空格也算
            // NodeList childlist = nodelist.item(i).getChildNodes();
            //                
            // for(int j = 0; j < childlist.getLength();j++) {
            // System.out.println(childlist.item(j).getNodeName());
            // }
            //                
            // }

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 做循环使用
     *
     * @param root
     *            传入的元素
     */
    public static void Iterator(Element root) {
        NodeList nodelist = root.getChildNodes();
        for (int i = 0; i < nodelist.getLength(); i++) {
            Node node = nodelist.item(i);

            if (node instanceof Text) {
                String value = node.getNodeValue();

                if (value != null && !value.trim().equals("")) {
                    System.out.println("文本:" + value);

                }
            }
            if (node instanceof Element) {
                System.out.println("节点:" + node.getNodeName());
                Iterator((Element) node);
            }

        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值