java dom 读取xml文件,java读取XML文件里面的数据之DOM实现

本文档介绍了一个Java类ReadXML,用于读取并解析XML文件。通过DocumentBuilderFactory和DocumentBuilder,该类能够获取XML文档的DOM表示,并提供了一个方法获取指定标签名的节点信息。在遍历节点时,注意检查子节点是否存在以避免NullPointerException。
摘要由CSDN通过智能技术生成

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import java.io.*;

public class ReadXML {

private File file;

public ReadXML(String filename){

File file=new File(filename);

this.file=file;

}

/**

*

* @return the instance of Document

*/

public Document getDOM(){

DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

DocumentBuilder db;

Document document=null;

try{

db=dbf.newDocumentBuilder();

document=db.parse(file);

}catch(Exception e ){

e.printStackTrace();

}

return document;

}

/**

*

* @param tagName

* @return

*/

public String getInfoByTagName(String tagName)

{

String info="";

Document document=this.getDOM();

//获取NodeName 为tagName的节点组

NodeList nl=document.getElementsByTagName(tagName);

for(int i=0;i

{

info+=tagName+"[+"+i+"+]"+"\n";

Node node=nl.item(i);

//如果当前节点有子节点(这里 只考虑还有一级子节点的情况)

if(node.hasChildNodes())

{

NodeList list=node.getChildNodes();

for(int j=0;j

{

Node childNode=list.item(j);

/* 不加这个If语句会抛出

* Exception in thread "main" java.lang.NullPointerException

* at ReadXML.getInfoByTagName(ReadXML.java:59)

* at Test.main(Test.java:17)

*/

if(childNode.getFirstChild()!=null)

/* 对getNodeValue()的过程彻底无语

* 调试这个地方的时候,在网上很容易找到了

* 在得到Value的时候必须在节点对象后面先调用getFirstChild()或者getChildNodes().item(0)

* 原因很简单,但是不知道设计者问什么要这么设计

* 最近在看《Be

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值