java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE, JavaME, JavaSE)的总称。本站提供基于Java框架struts,spring,hibernate等的桌面应用、web交互及移动终端的开发技巧与资料

保持永久学习的心态,将成就一个优秀的你,来 继续搞起java知识。

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){

//判断此节点是否为一个元素节点对象:

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

Node n=list.item(i);

readnode(n);

}

}

}

}

}

/**

* 打印出本节点的属性

* @param node 节点对象

*/

public void readAttr(Node node){

if(null != node){

//判断此节点是否为一个元素节点对象:

if(Node.ELEMENT_NODE==node.getNodeType()){

//获取节点属性集合

NamedNodeMap list=node.getAttributes();

if(null !=list){

for(int i=0;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);

}

}

Cookie

因为水平有限,难免有疏忽或者不准确的地方,希望大家能够直接指出来,我会及时改正。一切为了知识的分享。

后续会有更多的精彩的内容分享给大家。