read xml

package com.rss.rssparser;

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

public class XMLReader{
//Document可以看作是XML在内存中的一个镜像,那么一旦获取这个Document 就意味着可以通过对
//内存的操作来实现对XML的操作,首先第一步获取XML相关的Document
private Document doc=null;

public void init(String xmlFile) throws Exception{
//很明显该类是一个单例,先获取产生DocumentBuilder工厂
//的工厂,在通过这个工厂产生一个DocumentBuilder,
//DocumentBuilder就是用来产生Document的
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
//这个Document就是一个XML文件在内存中的镜像
doc=db.parse(new File(xmlFile));
}
//该方法负责把XML文件的内容显示出来
public void viewXML(String xmlFile) throws Exception{
this.init(xmlFile);
//在xml文件里,只有一个根元素,先把根元素拿出来看看
Element element=doc.getDocumentElement();
System.out.println("根元素为:"+element.getTagName());

NodeList nodeList=doc.getElementsByTagName("item");
System.out.println("item节点链的长度:"+nodeList.getLength());


System.out.println("----------");
for(int i=0;i<nodeList.getLength();i++){
Node fatherNode=nodeList.item(i);
NodeList childNodes = fatherNode.getChildNodes();
System.out.println("childNodes.getLength()=: "+childNodes.getLength());
for(int j=0;j<childNodes.getLength();j++){

Node childNode=childNodes.item(j);
// System.out.println(childNode.getBaseURI());
//如果这个节点属于Element ,再进行取值
if(childNode instanceof Element){
System.out.println(j+"==");
System.out.println("子节点名为:"+childNode.getNodeName()+"相对应的值为"+childNode.getFirstChild().getNodeValue());
}
}
}
System.out.println("----------");


}

public static void main(String[] args)throws Exception{
XMLReader parse=new XMLReader();

//我的XML文件
parse.viewXML("D:/workspace/Rss/rss.xml");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值