java xml解析工具类_使用Java自带DOM工具解析XML

包括三个文件:studentInfo.xml(待解析的xml文件),DomBuilder.java(解析的主要类),TestDomBuilder.java(测试解析的结果),代码分别如下(由于使用csdn blog自带的代码粘贴工具会朝里加入一些"..."字符,虽然利于查看,但是不利于把代码copy出来运行,而亲自运行代码对程序员来说是很重要的,故没有使用csdn blog自带的代码粘贴工具来插入代码,而是用着用直白的方式):

studentInfo.xml

崔卫兵

PC学院

62354666

男,1982年生,硕士,现就读于北京邮电大学

cwb

PC学院

62358888

男,1987年生,硕士,现就读于中国农业大学

xxxxx

xxx学院

66666666

注视中,注释中

yyyyyy

yyyy学院

88888888

注视中111,注释中222

DomBuilder.java

package domExample;

import java.util.HashMap;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

/**

* 用java自带的DOM工具实现对xml的编程

*

* @author cuiweibing

* @since 2007.8.9

*/

public class DomBuilder {

/**

* 执行具体的解析工作

* @param filename,待解析的既定格式的xml文件名(相对路径或者决定路径)

* @param hm      ,HashMap 存放解析后的结果,供后继使用

*/

/**

* @param filename

* @param hm

*/

public void executeParser(String filename,HashMap hm){

DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();

try {

//产生解析实例

DocumentBuilder dombuilder = domfac.newDocumentBuilder();

//把XML文件读入放在FileInputStream中,并用其父类InputStream的实例接受

InputStream is = new FileInputStream(filename);

//根据输入XML文件流解析成Document结构,供下面遍历与操作使用

Document doc = dombuilder.parse(is);

//获取根结点student

Element root = doc.getDocumentElement();

NodeList persons = root.getChildNodes();

//用于记录学生编号的变量

int num=-1;

if (persons != null) {

//遍历所有person节点

for (int i = 0; i < persons.getLength(); i++) {

Node person = persons.item(i);

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

num++;

// 获取person节点的age属性的值

Node personNode=person.getAttributes().getNamedItem("age");

if(personNode!=null){

String age = personNode.getNodeValue();

if (age != null&&!age.equals("")) {

hm.put(person.getNodeName() + "-age" + num, age);

} else {

hm.put(person.getNodeName() + "-age" + num, "20");

}

}else {

hm.put(person.getNodeName() + "-age" + num, "20");

}

//遍历所有person节点的子节点

for (Node node = person.getFirstChild(); node != null; node = node

.getNextSibling()) {

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

// 处理person节点的子节点name

if (node.getNodeName().equals("name")) {

String name = node.getNodeName();

//不可用此,dom中也认为崔卫兵中的"崔卫兵"也是节点,而且是name节点的子节点,不同于SAX

//String name = node.getNodeValue();

String nameValue = node.getFirstChild().getNodeValue();

hm.put(name + num, nameValue);

}

// 处理person节点的子节点college

else if (node.getNodeName().equals("college")) {

String name = node.getNodeName();

String nameValue = node.getFirstChild().getNodeValue();

hm.put(name + num, nameValue);

//获取college节点的leader属性的值

Node leaderNode=node.getAttributes().getNamedItem("leader");

if(leaderNode!=null){

String leader = leaderNode.getNodeValue();

if (leader != null&&!leader.equals("")) {

hm.put(node.getNodeName() + "-leader" + num, leader);

} else {

hm.put(node.getNodeName() + "-leader" + num, "leader");

}

}else {

hm.put(node.getNodeName() + "-leader" + num, "leader");

}

}

//处理person节点的子节点telephone

else if (node.getNodeName().equals("telephone")) {

String name = node.getNodeName();

String nameValue = node.getFirstChild().getNodeValue();

hm.put(name + num, nameValue);

}

//处理person节点的子节点notes

else if (node.getNodeName().equals("notes")) {

String name = node.getNodeName();

String nameValue = node.getFirstChild().getNodeValue();

hm.put(name + num, nameValue);

}

}

}

}

}

}

} catch (ParserConfigurationException e) {

e.printStackTrace();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 构造函数

*/

public DomBuilder() {

}

}

TestDomBuilder.java

package domExample;

import java.util.HashMap;

/**

* 测试DomBuilder解析的情况

* @author cuiweibing

* @since 2007.8.9

*/

public class TestDomBuilder {

public static void main(String[] args) {

try{

//获取解析完后的解析信息

HashMap hashMap = new HashMap();

DomBuilder db=new DomBuilder();

db.executeParser("studentInfo.xml", hashMap);

System.out.println("姓名/t年龄/t学院/t学院领导/t电话/t/t备注");

for(int i=0;i

int j=i/6;

System.out.print(hashMap.get("name"+j)+"/t");

System.out.print(hashMap.get("person-age"+j)+"/t");

System.out.print(hashMap.get("college"+j)+"/t");

System.out.print(hashMap.get("college-leader"+j)+"/t");

System.out.print(hashMap.get("telephone"+j)+"/t");

System.out.println(hashMap.get("notes"+j)+"/t");

}

}catch(Exception ex){

ex.printStackTrace();

}

}

}

运行结果

姓名 年龄 学院 学院领导 电话  备注崔卫兵 25 PC学院 leader 62354666 男,1982年生,硕士,现就读于北京邮电大学 cwb 20 PC学院 leader1 62358888 男,1987年生,硕士,现就读于中国农业大学 xxxxx 45 xxx学院 leader 66666666 注视中,注释中 yyyyyy 20 yyyy学院 学院领导 88888888 注视中111,注释中222

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * 本类是专门解析XML文件的,主要用于为系统读取自己的配置文件时提供最方便的解析操作 * @author HX * */ public class XmlManager { /** * 得到某节点下某个属性的值 * @param element 要获取属性的节点 * @param attributeName 要取值的属性名称 * @return 要获取的属性的值 * @author HX_2010-01-12 */ public static String getAttribute( Element element, String attributeName ) { return element.getAttribute( attributeName ); } /** * 获取指定节点下的文本 * @param element 要获取文本的节点 * @return 指定节点下的文本 * @author HX_2010-01-12 */ public static String getText( Element element ) { return element.getFirstChild().getNodeValue(); } /** * 解析某个xml文件,并在内存中创建DOM树 * @param xmlFile 要解析XML文件 * @return 解析某个配置文件后的Document * @throws Exception xml文件不存在 */ public static Document parse( String xmlFile ) throws Exception { // 绑定XML文件,建造DOM树 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document domTree = db.parse( xmlFile ); return domTree; } /** * 获得某节点下的某个子节点(指定子节点名称,和某个属性的值) * 即获取parentElement下名字叫childName,并且属性attributeName的值为attributeValue的子结点 * @param parentElement 要获取子节点的那个父节点 * @param childName 要获取的子节点名称 * @param attributeName 要指定的属性名称 * @param attributeValue 要指定的属性的值 * @return 符合条件的子节点 * @throws Exception 子结点不存在或有多个符合条件的子节点 * @author HX_2008-12-01 */ public static Element getChildElement( Element parentElement, String childName, String attributeName, String attributeValue ) throws Exception { NodeList list = parentElement.getElementsByTagName( childName ); int count = 0; Element curElement = null; for ( int i = 0 ; i < list.getLength() ; i ++ ) { Element child = ( Element )list.item( i ); String value = child.getAttribute( attributeName ); if ( true == value.equals( attributeValue ) ) { curElement =

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值