前端之家收集整理的这篇文章主要介绍了
document方式解析xml文件,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
404_0@
/**
* @FILE:Test.java
* @AUTHOR:Administratorbaifan
* @DATE:2013-4-14 下午6:23:56
**/
package com.yehui.test;
import java.io.File;
import java.io.IOException;
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;
/*******************************************
* @COMPANY:lingan
* @CLASS:Test
* @DESCRIPTION:使用document方式解析xml文件
* @AUTHOR:Administrator
* @VERSION:v1.0
* @DATE:2013-4-14 下午6:23:56
*******************************************/
public class Javaxml {
private File f;
static StringBuffer sbf = new StringBuffer();
/**
* docuemnt :xml文件的document
*/
private Document docuemnt;
/**
* db :DocumentBuilder抽象类对象,不可以实例化,借助DocumentBuilderFactory类实例化
*/
private DocumentBuilder db;
private DocumentBuilderFactory dbf;
/**
* elment :根节点
*/
private Element elment;
/**
* content :xml文件的内容
*/
public String content;
public Javaxml(File f) {
try {
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
this.f = f;
// 解析xml文件
this.docuemnt = db.parse(f);
// 获得根节点
elment = docuemnt.getDocumentElement();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File f = new File("a.xml");
Javaxml jx = new Javaxml(f);
printstr(jx.elment,"code");
System.out.println(sbf.toString());
}
/**
* @description: 这里使用了递归的方法获取xml文件中的某个节点下的内容
* @author:Administrator
* @return:String
*/
public static String printstr(Node node,String nodeName) {
// nodeName的子节点
NodeList nodelist = null;
nodelist = node.getChildNodes();
if (nodeName.equals(node.getNodeName())) {
for (int i = 0; i < nodelist.getLength(); i++) {
// nodelist.item(i).getTextContent()获得子节点的内容
sbf.append(nodelist.item(i).getTextContent()).append(",");
}
} else {
if (nodelist != null) {
for (int i = 0; i < nodelist.getLength(); i++) {
Node tmp = nodelist.item(i);
printstr(tmp,nodeName);
}
}
}
return sbf.toString();
}
}
xml文件
@H_
404_0@<?xml version="1.0" encoding="gbk"?>
<Accounts>
<Account type="by0003">
<code>100001</code>
<pass>123</pass>
<name>李四</name>
<money>1000000.00</money>
</Account>
<Account type="hz0001">
<code>100002</code>
<pass>123</pass>
<name>张三</name>
<money>1000.00</money>
</Account>
</Accounts>
运行结果
原文链接:https://www.f2er.com/xml/300632.html