递归打印XML文档树-使用w3cDOM模型解析

本文介绍如何利用w3c DOM模型解析XML文件,将内存中的Document对象以递归方式输出到控制台,详细阐述了相关API的使用方法。

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

如题,使用w3c xml parse api来把内存中的Document文档树对象打印到控制台

package xml;

import java.io.InputStream;

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

import org.w3c.dom.Attr;
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 TestXml {

	public static void main(String[] args) throws Exception {
		Class<TestXml> testXmlClazz = TestXml.class;
		InputStream is = testXmlClazz.getResourceAsStream("???.xml");
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(is);
		Element root = doc.getDocumentElement();
		parseElement(root);
	}

	private static void parseElement(Element ele) {
		System.out.print("<" + ele.getTagName());
		// 打印标签的属性
		NamedNodeMap attris = ele.getAttributes();
		for(int i = 0; i < attris.getLength(); i++) {
			Attr attr = (Attr) attris.item(i);
			System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
		}
		System.out.println(">");
		// 获取子标签
		NodeList childNodes = ele.getChildNodes();
		for (int i = 0; i < childNodes.getLength(); i++) {
			Node childNode = childNodes.item(i);
			if (childNode.getNodeType() == Node.ELEMENT_NODE) {
				// 递归处理子标签
				parseElement((Element) childNode);
			} else if (childNode.getNodeType() != Node.COMMENT_NODE) {
				System.out.println(childNode.getTextContent().trim());
			}
		}
		System.out.println("</" + ele.getTagName() + ">");
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值