java怎么读取一个java 读取xml文件 sax

博客分类:
一直都在使用dom的方式读取xml文件,但如果稍大点的xml文件那么dom方式就有点不太适合。
研究了下jdk的api,用dom和sax方式的解析结果做了个对比
要解析的xml内容格式如下
&?xml version="1.0" encoding="UTF-8"?&
&loc&商品链接访问地址&/loc&
&title&商品名称&/title&
&price&价格&/price&
商品图片访问地址
&description&商品描述&/description&
&barCode&条形码值&/barCode&
&area&产地 (北京)&/area&
&producedate&生产日期 ()&/producedate&
&manufacturers&生产厂家
(某某某)&/manufacturers&
&/display&
//.....更更多
xml文件大小16.5M
首先是dom方式读取,代码如下
package test.
import java.util.ArrayL
import java.util.HashM
import java.util.L
import java.util.M
import java.util.S
import javax.xml.parsers.DocumentBuilderF
import org.w3c.dom.D
import org.w3c.dom.E
import org.w3c.dom.N
import org.w3c.dom.NodeL
public class JDKBigXmlDomParse {
private int statmentSize = 6;
private List&Map&String, Object&& dataList = new ArrayList&Map&String, Object&&(statmentSize);
public void test() throws Exception{
String uri = "f:\\test.xml";
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(uri);
NodeList urls = doc.getElementsByTagName("url");
int length = urls.getLength();
for(int i=0;i&i++){
Node node = urls.item(i);
if(node.getNodeType() != Node.ELEMENT_NODE){
Element urlElement = (Element)
Map&String,Object& entry = parseEntity(urlElement);
if(!entry.isEmpty()){
dataList.add(entry);
if(dataList.size() == statmentSize){
doSomeThing();
private Map&String,Object& parseEntity(Element element){
Map&String,Object& map = new HashMap&String, Object&();
map.put("loc", getElementValueByTagName(element,"loc"));
map.put("title", getElementValueByTagName(element,"title"));
map.put("price", getElementValueByTagName(element,"price"));
map.put("image", getElementValueByTagName(element,"image"));
map.put("description", getElementValueByTagName(element,"description"));
map.put("barCode", getElementValueByTagName(element,"barCode"));
map.put("area", getElementValueByTagName(element,"area"));
map.put("producedate", getElementValueByTagName(element,"producedate"));
map.put("manufacturers", getElementValueByTagName(element,"manufacturers"));
private String getElementValueByTagName(Element element,String tagName){
NodeList nodeList = element.getElementsByTagName(tagName);
String value = "";
if(nodeList.getLength() != 0){
Node node = nodeList.item(0);
value = node.getFirstChild().getNodeValue().trim();
private void doSomeThing(){
//printMapList(dataList);
dataList.clear();
private void printMapList(List&Map&String,Object&& dataList){
boolean first =
for(Map&String,Object& map:dataList){
System.out.println();
System.out.print("{");
Set&Map.Entry&String, Object&& entries = map.entrySet();
for(Map.Entry&String, Object& entry:entries){
if(!first){
System.out.print(",");
System.out.print("\""+entry.getKey()+"\":");
System.out.print("\""+entry.getValue()+"\"");
System.out.print("}");
System.out.println();
public static void main(String[] args) throws Exception{
long start = System.nanoTime();
new JDKBigXmlDomParse().test();
long end = System.nanoTime();
System.out.println("耗时:"+(end-start)/.0+"秒");
运行结果:
sax方式读取,代码如下:
package test.
import java.io.FileInputS
import java.io.InputS
import java.util.ArrayL
import java.util.HashM
import java.util.L
import java.util.M
import java.util.S
import javax.xml.parsers.SAXP
import javax.xml.parsers.SAXParserF
import mons.lang.StringU
import org.xml.sax.A
import org.xml.sax.SAXE
import org.xml.sax.helpers.DefaultH
public class JDKBigXmlSaxParse extends DefaultHandler {
private int statmentSize = 6;
private List&Map&String, Object&& dataList = new ArrayList&Map&String, Object&&(statmentSize);
private Map&String, Object& dataM
private String currentTag = "";
public void test() throws Exception {
SAXParser sax = SAXParserFactory.newInstance().newSAXParser();
InputStream in = new FileInputStream("f:\\test.xml");
sax.parse(in, this);
in.close();
public void characters(char[] ch, int start, int length)throws SAXException {
String value = new String(ch, start, length);
if(!StringUtils.isBlank(value)){
dataMap.put(currentTag, value.trim());
public void endElement(String uri, String localName, String qName)
throws SAXException {
if("url".equals(qName)){
dataList.add(dataMap);
//dataMap.clear();
if(dataList.size() == statmentSize){
doSomeThing();
dataList.clear();
if("urlset".equals(qName) && dataList.size() != 0){
doSomeThing();
dataList.clear();
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if ("url".equals(qName)) {
dataMap = new HashMap&String, Object&();
currentTag = qN
public static void main(String[] args) throws Exception {
long start = System.nanoTime();
new JDKBigXmlSaxParse().test();
long end = System.nanoTime();
System.out.println("耗时:"+(end-start)/.0+"秒");
public void doSomeThing(){
//printMapList(dataList);
private void printMapList(List&Map&String,Object&& dataList){
boolean first =
for(Map&String,Object& map:dataList){
System.out.println();
System.out.print("{");
Set&Map.Entry&String, Object&& entries = map.entrySet();
for(Map.Entry&String, Object& entry:entries){
if(!first){
System.out.print(",");
System.out.print("\""+entry.getKey()+"\":");
System.out.print("\""+entry.getValue()+"\"");
System.out.print("}");
System.out.println();
运行结果:
可以看到dom消耗的时间是sax方式的5倍。结论:如果只是读取xml文件,还是sax方式强。。。
而且在eclipse里面用dom方式运行的时候可能会出现eclipse java.lang.OutOfMemoryError: Java heap space这个问题
酷的飞上天空
浏览: 358639 次
来自: 无锡
spring mvc demo教程源代码下载,地址:http: ...
haiyinlong 写道private File value ...
分析很难,好的规则持久,靠某个方法条件局限不能证明长久
当事件发生的时候,事件多个细节证明因素要被单独分析,这样能够分 ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'用户名:tangyujing
文章数:22
访问量:10834
注册日期:
阅读量:1297
阅读量:3317
阅读量:581908
阅读量:466482
51CTO推荐博文
本人是在jsp中写java文件,读取xml文件中的内容,并在页面显示。tangyj1.下载jar包2.写xml文件3.在jsp中写java读取xml内容&%@pageimport="org.jdom2.Document"%&&%@pageimport="org.jdom2.input.SAXBuilder"%&&%@pageimport="org.jdom2.output.Format"%&&%@pageimport="org.jdom2.output.XMLOutputter"%&&%@pageimport="org.jdom2.Element"%&&%@pageimport="java.io.*"%&&%@pageimport="java.util.*"%&650) this.width=650;" src="/e/u/themes/default/images/spacer.gif" style="border:1px solid #" alt="spacer.gif" />加入jar包jdom.jar&%String path=pageContext.getServletContext().getRealPath("version.xml");
System.out.println(path+"----------------7----==---");
SAXBuilder sb =newSAXBuilder();// 新建立构造器 Document doc1 = sb.build(newFileInputStream(path));
Element root1=doc1.getRootElement();
String smtpusername="";//用户名
String smtppwd="";//密码
String smtpserver="";//邮件服务器域名 Listlist1=root1.getChildren("person"); for(intii=0;ii&list1.size();ii++){
Element element=(Element)list1.get(ii);
smtpusername=element.getChildText("name");
smtppwd=element.getChildText("ver");
smtpserver=element.getChildText("publish");
System.out.println(smtpusername+"--"+smtppwd+"--"+smtpserver);
} %&将你读取的内容,在jsp页面用&%=smtpserver&显示即可//这个是建立的xml文件version.xml在我的根目录下,就是项目启动部署的目录&?xmlversion="1.0"encoding="UTF-8"?&&version&&personid="01"&&name&lhl&/name&&ver&v1.0&/ver&&publish&&/publish&&company&zkr&/company&&/person&&personid="01"&&name&tangyj&/name&&ver&v1.1&/ver&&publish&&/publish&&company&zkr&/company&&/person&&/version&本文出自 “” 博客,请务必保留此出处
了这篇文章
类别:未分类┆阅读(0)┆评论(0)Java(19)
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class readxml {//定义一个java类
& &public static void main(String[] args) {
& & & &DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//创建一个&DocumentBuilderFactory实例
& & & &try{
& & & & & &DocumentBuilder db = dbf.newDocumentBuilder();//创建DocumentBuilder实例
& & & & & &Document doc = db.parse(&pet2.xml&);//读取pet2.xml文件,此时的xml文件默认放在java项目的第一级文件夹下
& & & & & &NodeList dogList = doc.getElementsByTagName(&dog&);//获得标签dog的元素
& & & & & &System.out.println(&共有& + dogList.getLength() + &个dog节点&);//计算dog节点的个数
& & & & & &for (int i = 0; i & dogList.getLength(); i++)
& & & & & &{//遍历dog节点
& & & & & & & &Node dog = dogList.item(i);//获取当前的一个dog节点
& & & & & & & &Element elem = (Element)//获取该dog节点的元素
& & & & & & & &System.out.println(&id:& + elem.getAttribute(&id&));//打印该dog节点的属性id的值
& & & & & & & &for (Node node = dog.getFirstChild(); node != node = node.getNextSibling())//遍历该dog节点的所有孩子节点
& & & & & & & &{
& & & & & & & & & &if (node.getNodeType() == Node.ELEMENT_NODE)
& & & & & & & & & &{
& & & & & & & & & & & &String name = node.getNodeName();//获得dog节点的孩子节点的名字
& & & & & & & & & & & &String value = node.getFirstChild().getNodeValue();//获得dog节点的孩子节点的值
& & & & & & & & & & & &System.out.print(name + &:& + value + &\t&);//打印该dog节点的某一个孩子节点的信息
& & & & & & & & & &}
& & & & & & & &}
& & & & & & & &System.out.println();
& & & & & &}
& & & &}catch (Exception e)
& & & & & &e.printStackTrace();
pet2.xml文件的内容:
& & & &&dog id=&1&& & & & &&
& & & & & &&name&Delphi&/name&
& & & & & &&health&210&/health&
& & & & & &&love&0&/love&
& & & & & &&strain&在天山脚下&/strain&
& & & &&/dog&
& & & &&dog id=&2&& & & & &&
& & & & & &&name&VC++&/name&
& & & & & &&health&590&/health&
& & & & & &&love&15&/love&
& & & & & &&strain&在太阳系中心&/strain&
& & & &&/dog&
& &&/dogs&
& &&penguins&
& & & &&penguin id=&3&& & & & &&
& & & & & &&name&IOS&/name&
& & & & & &&health&990&/health&
& & & & & &&love&20&/love&
& & & & & &&sex&在地心以内&/sex& & & & & &&
& & & &&/penguin& & & &&
& &&/penguins&
运行该程序的结果:
共有2个dog节点
name:Delphi health:210
love:0 strain:在天山脚下
name:VC++ health:590
love:15 strain:在太阳系中心
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:151710次
积分:2672
积分:2672
排名:第13900名
原创:116篇
转载:51篇
评论:14条
(6)(28)(2)(1)(1)(1)(4)(4)(3)(4)(9)(7)(2)(7)(19)(30)(9)(4)(7)(14)(1)(2)(2)
(window.slotbydup = window.slotbydup || []).push({
id: '4740887',
container: s,
size: '250,250',
display: 'inlay-fix'Java如何读取XML文件 具体实现
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了Java如何读取XML文件 具体实现,有需要的朋友可以参考一下
今天的CSDN常见问题来讲解下在Java中如何读取XML文件的内容。
直接上代码吧,注释写的很清楚了!
代码如下:import java.io.*;import javax.xml.parsers.DocumentBimport javax.xml.parsers.DocumentBuilderFimport org.w3c.dom.Dimport org.w3c.dom.Eimport org.w3c.dom.Nimport org.w3c.dom.NodeL
public class XMLReaderTest {
&public static void main(String args[]) {&&Element element =&&// 可以使用绝对路劲&&File f = new File("test.xml");
&&// documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件)&&DocumentBuilder db =&&DocumentBuilderFactory dbf =&&try {&&&// 返回documentBuilderFactory对象&&&dbf = DocumentBuilderFactory.newInstance();&&&// 返回db对象用documentBuilderFatory对象获得返回documentBuildr对象&&&db = dbf.newDocumentBuilder();
&&&// 得到一个DOM并返回给document对象&&&Document dt = db.parse(f);&&&// 得到一个elment根元素&&&element = dt.getDocumentElement();&&&// 获得根节点&&&System.out.println("根元素:" + element.getNodeName());
&&&// 获得根元素下的子节点&&&NodeList childNodes = element.getChildNodes();
&&&// 遍历这些子节点&&&for (int i = 0; i & childNodes.getLength(); i++) {&&&&// 获得每个对应位置i的结点&&&&Node node1 = childNodes.item(i);&&&&if ("Account".equals(node1.getNodeName())) {&&&&&// 如果节点的名称为"Account",则输出Account元素属性type&&&&&System.out.println("\r\n找到一篇账号. 所属区域: " + node1.getAttributes().getNamedItem("type").getNodeValue() + ". ");&&&&&// 获得&Accounts&下的节点&&&&&NodeList nodeDetail = node1.getChildNodes();&&&&&// 遍历&Accounts&下的节点&&&&&for (int j = 0; j & nodeDetail.getLength(); j++) {&&&&&&// 获得&Accounts&元素每一个节点&&&&&&Node detail = nodeDetail.item(j);&&&&&&if ("code".equals(detail.getNodeName())) // 输出code&&&&&&&System.out.println("卡号: " + detail.getTextContent());&&&&&&else if ("pass".equals(detail.getNodeName())) // 输出pass&&&&&&&System.out.println("密码: " + detail.getTextContent());&&&&&&else if ("name".equals(detail.getNodeName())) // 输出name&&&&&&&System.out.println("姓名: " + detail.getTextContent());&&&&&&else if ("money".equals(detail.getNodeName())) // 输出money&&&&&&&System.out.println("余额: " + detail.getTextContent());&&&&&}&&&&}
&&catch (Exception e) {&&&e.printStackTrace();&&}&}}
然后我们测试的XML文件(test.xml)要放在项目工程的根目录下,其内容是:
代码如下:&?xml version="1.0" encoding="gbk"?&&Accounts&&&Account type="type1"&&&&code&100001&/code&&&&pass&123&/pass&&&&name&李四&/name&&&&money&&/money&&&/Account&&&Account type="type2"&&&&code&100002&/code&&&&pass&123&/pass&&&&name&张三&/name&&&&money&1000.00&/money&&&/Account&&/Accounts&
直接运行代码,输出:
根元素:Accounts
找到一篇账号. 所属区域: type1. 卡号: 100001密码: 123姓名: 李四余额:
找到一篇账号. 所属区域: type2. 卡号: 100002密码: 123姓名: 张三余额: 1000.00
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具Java中的XML操作
视频太卡?试试切换线路
本课时介绍XML数据格式,XML,即可扩展标记语言(Extensible Markup Language),标准通用标记语言的子集,一种用于标记电子文件使其具有结构性的标记语言。它可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。
本课讲解使用DocumentBuilder的Parse方法解析XML数据位Document对象,并进一步解析其内部数据。
本课讲解使用Document创建XML数据,并通过Transformer将其转换为String字符串输出。
本课讲解使用第三方的Dom4j库操作XML数据,可以大大简化代码量,并且降低操作难度。
只有成为VIP会员才能提问&回复,快吧!如果你还没有账号你可以一个账号。
添加新技术问题
课程 [XML数据格式简介]
中已存在问题
添加新技术问题
问题描述越详细,被解答的速度越快
有新回答时请邮件提醒我
着急,拜托快点
不急,慢慢解决
关联课程 [XML数据格式简介]

我要回帖

更多关于 java 读取sql xml文件 的文章

 

随机推荐