Java 使用DOM解析xml文件

本文提供了一个Java中使用DOM解析XML文件的示例代码,通过解析不同类型的XML节点并打印相关信息,帮助初学者理解DOM的基本操作。

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

程序来源:Java2 编程150例
下面的代码可以直接跑,希望能为初学使用DOM解析xml文件的朋友节省时间


package parseXML;

import java.io.File;
import java.io.IOException;

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

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class DOMDemo2 {

DOMDemo2(){
super();
}
private void print(Node node){
System.out.println("节点名:"+node.getNodeName());
String value=node.getNamespaceURI();
if(value!=null){
System.out.println("节点URL:"+value);
}
value=node.getNodeValue();
if(value!=null){
System.out.println("节点值:"+value);
}
}

private void echo(Node node){ //Node是很多元素的父类
int type = node.getNodeType();
switch(type){
case Node.ATTRIBUTE_NODE:
System.out.println("这是个ATTR!!");
print(node);
break;
case Node.DOCUMENT_FRAGMENT_NODE:
System.out.println("这是个Doc_fragment!!");
print(node);
break;
case Node.COMMENT_NODE:
System.out.println("这是个comment!!");
print(node);
break;
case Node.ELEMENT_NODE:
System.out.println("这是个Element!!");
print(node);

NamedNodeMap atts = node.getAttributes();
for(int i = 0;i<atts.getLength();i++){
Node att = atts.item(i); //返回第i项
echo(att);
}
break;
default:
System.out.println("这是个未知节点:"+type);
print(node);
}
//遍历:从根节点开始,往下一个孩子一个孩子的遍历
for(Node child = node.getFirstChild();
child!=null;child=child.getNextSibling()){
echo(child);
}
}
public static void main(String[] args) {

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try{
db = dbf.newDocumentBuilder();
}catch(ParserConfigurationException pce){
System.err.println(pce.toString());
}
String fileName = "parseXML/test.xml";
Document doc = null;
try{
doc = db.parse(new File(fileName)); //public interface Document extends Node
}catch(IOException ioe){
System.err.println(ioe.toString());
}catch(SAXException se){
System.err.println(se.toString());
}

DOMDemo2 dd = new DOMDemo2();
dd.echo(doc);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值