DocumentBuilder 递归解析xml,适合android 以及java

本文提供了一个使用Java解析XML文件的示例代码,包括解析文件、获取根元素、遍历元素及其属性和子元素等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package cn;

import java.io.File;

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

import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Test {
    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document doc = db.parse(new File("d:\\catelog.xml"));
        // 获取根元素节点
        Element root = doc.getDocumentElement();

        parseElement(root);
    }

    static void parseElement(Element element) {
        String tagName = element.getNodeName();

        System.out.print("<" + tagName);
        // element元素的所有属性构成的NamedNodeMap对象,需要对其进行判断
        NamedNodeMap map = element.getAttributes();
        // 如果存在属性,则打印属性
        if (null != map) {
            for (int i = 0; i < map.getLength(); i++) {
                // 获得该元素的每一个属性
                Attr attr = (Attr) map.item(i);
                // 属性名和属性值
                String attrName = attr.getName();
                String attrValue = attr.getValue();
                // 注意属性值需要加上引号,所以需要\转义
                System.out.print(" " + attrName + "=\"" + attrValue + "\"");
            }
        }

        // 关闭标签名
        System.out.print(">");

        // 至此已经打印出了元素名和其属性
        // 下面开始考虑它的子元素
        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            // 获取每一个child
            Node node = children.item(i);
            // 获取节点类型
            short nodeType = node.getNodeType();

            if (nodeType == Node.ELEMENT_NODE) {
                // 如果是元素类型,则递归输出
                parseElement((Element) node);
            } else if (nodeType == Node.TEXT_NODE) {
                // 如果是文本类型,则输出节点值,及文本内容
                System.out.print(node.getNodeValue());
            } else if (nodeType == Node.COMMENT_NODE) {
                // 如果是注释,则输出注释
                System.out.print("<!--");
                Comment comment = (Comment) node;
                // 注释内容
                String data = comment.getData();

                System.out.print(data);

                System.out.print("-->");
            }
        }

        // 所有内容处理完之后,输出,关闭根节点
        System.out.print("</" + tagName + ">");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值