readXML

package org.doc;

import java.io.InputStream;

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

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXmlDoc {
public static DocumentBuilderFactory domfac;
static{
domfac =
DocumentBuilderFactory.newInstance();
}
/**
* 通过此方法 可以得到document解析器
* @return 返回doc解析器
* @throws Exception
*/
public DocumentBuilder getDocumentBuilder()throws Exception{
DocumentBuilder dombuilder = domfac.newDocumentBuilder();
return dombuilder;
}
/**
* 得到项目下xml文件的document对象
* @param path xml文件名称
* @return 得到document对象
* @throws Exception
*/
public Document getDocument(String path)throws Exception{
InputStream is=ReadXmlDoc.class.getClassLoader().getResourceAsStream(path);
//InputStream is = new FileInputStream("E:\\java练习\\library.xml");
Document doc = getDocumentBuilder().parse(is);
return doc;
}
/**
* 解析打印出doc对象中所有节点的值
* @param doc 要解析的document对象
* @throws Exception
*/
public void readxml(Document doc)throws Exception{
//得到根节点对象
Node node=doc.getDocumentElement();
readnode(node);
}
/**
* 本方法传入一个节点对象,将会用递归方式遍历本节点
* 以及子节点所有的值
* @param node 节点对象
* @throws Exception
*/
public void readnode(Node node)throws Exception{
if(null != node){
//判断此节点是否为一个元素节点对象:<book></book>
if(Node.ELEMENT_NODE==node.getNodeType()){
System.out.println("节点名称: " +
node.getNodeName());
readAttr(node);
//获取子节点
NodeList list=node.getChildNodes();
if(list.getLength()<=1){
if(list.getLength()==1){
System.out.println("值: " +
node.getFirstChild().getNodeValue());
}
}
else{
for(int i=0;i<list.getLength();i++){
Node n=list.item(i);
readnode(n);
}
}
}
}
}
/**
* 打印出本节点的属性
* @param node 节点对象
*/
public void readAttr(Node node){
if(null != node){
//判断此节点是否为一个元素节点对象:<book></book>
if(Node.ELEMENT_NODE==node.getNodeType()){
//获取节点属性集合
NamedNodeMap list=node.getAttributes();
if(null !=list){
for(int i=0;i<list.getLength();i++){
Node n=list.item(i);
System.out.println(n.getNodeName()+" : "+n.getNodeValue());
}
}
}
}
}


/**
* @param args
*/
public static void main(String[] args)throws Exception {
ReadXmlDoc doc=new ReadXmlDoc();
Document d=doc.getDocument("test.xml");
doc.readxml(d);
// InputStream is=ReadXmlDoc.class.getClassLoader().getResourceAsStream("test.xml");
// System.out.println(ReadXmlDoc.class.getClassLoader().getResource("test.xml"));
// System.out.println(is);
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值