java遍历读取xml文件内容
作者:lry77 发布时间:2023-11-12 09:59:09
标签:java,遍历,读取,xml
本文实例讲解了java遍历读取xml文件内容的详细代码,分享给大家供大家参考,具体内容如下
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMComment;
import org.apache.axiom.om.OMContainer;
import org.apache.axiom.om.OMDataSource;
import org.apache.axiom.om.OMDocType;
import org.apache.axiom.om.OMDocument;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMProcessingInstruction;
import org.apache.axiom.om.OMSourcedElement;
import org.apache.axiom.om.OMText;
import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.xml.sax.helpers.XMLReaderFactory;
public class Axiomtest {
public static void main(String[] args) throws FileNotFoundException, Throwable {
// read xml
FileInputStream xmlFile = new FileInputStream("line-item2.xml");
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(xmlFile);
// 还需要StAXOMBuilder对象
StAXOMBuilder builder = new StAXOMBuilder(parser);
OMElement doc = builder.getDocumentElement(); // 读到<fool></fool>
OMElement cre = doc.getFirstChildWithName(new QName("student")); //读到<student>
OMElement cre1 = cre.getFirstChildWithName(new QName("id")); // 读到<id></id>
System.out.println(cre1.getLocalName()+":"+cre1.getText());
cre1 = cre.getFirstChildWithName(new QName("name")); // 读到<name></name>
System.out.println(cre1.getLocalName()+":"+cre1.getText());
cre1 = cre.getFirstChildWithName(new QName("age")); // 读到<age></age>
System.out.println(cre1.getLocalName()+":"+cre1.getText());
cre1 = cre.getFirstChildWithName(new QName("sex")); // 读到<sex></sex>
System.out.println(cre1.getLocalName()+":"+cre1.getText());
cre1 = cre.getFirstChildWithName(new QName("message")); // 读到<sex></sex>
System.out.println(cre1.getLocalName()+":"+cre1.getText());
System.out.println("------------------------------1");
Iterator<OMElement> iter = doc.getChildElements();
while(iter.hasNext()){
OMElement temp = iter.next();
System.out.println("====================");
System.out.println(temp.getLocalName());
// System.out.println(temp.getText());
if(temp.getLocalName().equals("student")){
Iterator<OMElement> iter1 = temp.getChildElements();
System.out.println("----------------");
while(iter1.hasNext()){
OMElement temp1 = iter1.next();
System.out.println(temp1.getLocalName()+":"+temp1.getText());
}
}
}
System.out.println("!!!!!!!!!!!!!");
FileInputStream file = new FileInputStream("line-item2.xml");
XMLStreamReader read = XMLInputFactory.newInstance().createXMLStreamReader(file);
StAXOMBuilder sta = new StAXOMBuilder(read);
OMElement all = sta.getDocumentElement();
Iterator<OMElement> ite1 = all.getChildElements();
while(ite1.hasNext()){
OMElement temp = ite1.next();
if(temp.getLocalName().equals("student")){
Iterator<OMElement> ite2 = temp.getChildElements();
while(ite2.hasNext()){
OMElement temp1 = ite2.next();
System.out.println(temp1.getLocalName()+":"+temp1.getText());
}
}
}
// write xml
OMFactory factory = OMAbstractFactory.getOMFactory();
//建立doc节点,doc节点会和下面的root节点合并
OMDocument dod = factory.createOMDocument();
//建立root节点
OMElement root = factory.createOMElement("root","","");
OMElement add = factory.createOMElement("dabi","","");
//建立两个普通节点
OMElement stu = factory.createOMElement("student","","");
stu.addChild(factory.createOMText("mac"));
OMElement tea = factory.createOMElement("teacher","","");
tea.addChild(factory.createOMText("silly"));
//构建树,将两个普通节点连到root节点上
root.addChild(stu);
root.addChild(tea);
//构建树,将root节点连到doc节点上
dod.addChild(root);
// 构建writer做输出器
XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(
new FileOutputStream("2.xml"));
root.serialize(writer); // cache on
writer.flush();
FileInputStream xmlFile1 = new FileInputStream("2.xml");
XMLStreamReader parser1 = XMLInputFactory.newInstance().createXMLStreamReader(xmlFile1);
StAXOMBuilder builder1 = new StAXOMBuilder(parser1);
OMElement doc1 = builder1.getDocumentElement();
Iterator<OMElement> iter1 = doc1.getChildElements();
while(iter1.hasNext()){
OMElement temp = iter1.next();
System.out.println("====================");
System.out.println(temp.getLocalName()+":"+temp.getText());
}
System.out.println("!!!!!!!!");
OMFactory omf = OMAbstractFactory.getOMFactory();
// OMDocument od = omf.createOMDocument();
OMElement root1 = omf.createOMElement("root","","");
OMElement name = omf.createOMElement("name","","");
OMElement sex = omf.createOMElement("sexy","","");
sex.addChild(omf.createOMText("man"));
name.addChild(omf.createOMText("dabi"));
root1.addChild(sex);
root1.addChild(name);
// od.addChild(root1);
XMLStreamWriter xmlw = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream("3.xml"));
root1.serialize(xmlw);
xmlw.flush();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<fool>
<student>
<name>mac</name>
<id>12</id>
<age>33</age>
<sex>male</sex>
<message>hello world</message>
</student>
<student>
<name>silly</name>
<id>5</id>
<age>12</age>
<sex>female</sex>
</student>
<teacher>
<name>Mr. Jones</name>
<id>2</id>
<age>31</age>
<sex>male</sex>
</teacher>
<student>
<name>macy</name>
<id>2</id>
<age>40</age>
<sex>female</sex>
</student>
<student>
<name>tom</name>
<id>32</id>
<age>31</age>
<sex>male</sex>
</student>
<message>hello world</message>
</fool>
再分享一例: 用JAVA读取XML文件
解析XML的步骤如下:
1.创建DocumentBuilder工厂
2.创建DocumentBuilder对象
3.DocumentBuilder对象的parse方法得到Document对象
4.Document对象的getElementsByTagName得到NodeList集合
5.通过getFirstChild和getNextSibling进行遍历
用到的包:
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
用到的对象:
DocumentBuilderFactory:创建DocumentBuilder的抽象工厂
DocumentBuilder:可以从 XML 获取一个 Document
Document:提供供对文档数据的基本访问
用到的方法:
DocumentBuilder.parse(String)':将给定 URI 的内容解析为一个 XML 文档,并且返回一个新的 DOM Document对象
Document.getElementsByTagName(String)':返回具有给定标记名称的所有 Element 的 NodeList
Element.getAttribute(String)':通过名称获得属性值
下面来解析一个XML文件
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class Test
{
public static void main(String[] args)
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("pet2.xml");
NodeList dogList = doc.getElementsByTagName("dog");
System.out.println("共有" + dogList.getLength() + "个dog节点");
for (int i = 0; i < dogList.getLength(); i++)
{
Node dog = dogList.item(i);
Element elem = (Element) dog;
System.out.println("id:" + elem.getAttribute("id"));
for (Node node = dog.getFirstChild(); node != null; node = node.getNextSibling())
{
if (node.getNodeType() == Node.ELEMENT_NODE)
{
String name = node.getNodeName();
String value = node.getFirstChild().getNodeValue();
System.out.print(name + ":" + value + "\t");
}
}
System.out.println();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
XML文件
<pets>
<dogs>
<dog id="1">
<name>YAYA</name>
<health>100</health>
<love>0</love>
<strain>酷酷的雪娜瑞</strain>
</dog>
<dog id="2">
<name>OUOU</name>
<health>90</health>
<love>15</love>
<strain>聪明的拉布拉多犬</strain>
</dog>
</dogs>
<penguins>
<penguin id="3">
<name>QQ</name>
<health>100</health>
<love>20</love>
<sex>Q仔</sex>
</penguin>
</penguins>
</pets>


猜你喜欢
- using System;using System.Web;using System.Web.Security;namespace Auth
- 编写程序,事先将所有观众姓名输入数组,然后获得数组元素的总数量,最后在数组元素中随机抽取元素的下标,根据抽取的下标获得幸运观众的姓名。思路如
- 本文实例为大家分享了Android仿大众点评星星评分控件的具体代码,供大家参考,具体内容如下话不多说,直接上代码,这里采用的是自定Viewp
- 本文实例为大家分享了java查找图中两点之间所有路径的具体代码,基于邻接表,供大家参考,具体内容如下图类:package graph1;im
- 本文实例为大家分享了Android实现拍照添加时间水印的具体代码,供大家参考,具体内容如下效果如下图 :1、拍照// 非空判断 拍照?if
- 作为最基础的引用数据类型,Java 设计者为 String 提供了字符串常量池以提高其性能,那么字符串常量池的具体原理是什么,我们带着以下三
- 1.背景由于公司的日志系统使用的是plumelog,最近生产环境老是报 jedis连接池不够,导致丢失日志,而且服务老是重启,怀疑跟日志系统
- 缘起:去年(大三上学期)比较喜欢写小游戏,于是想试着写个迷宫试一下。程序效果:按下空格显示路径:思考过程:迷宫由一个一个格子组成,要求从入口
- 指定创建派生类实例时应调用的基类构造函数;调用基类上已被其他方法重写的方法。注意:不能从静态方法中使用base关键字,base关键字只能在实
- 目录1. 支付宝支付接口(沙箱实现)1.1 支付宝沙箱账号获取1.2 下载客户端(目前好像只支持Android)1.3 代码配置1. 支付宝
- 现在由于GWF,google基本和咱们说咱见了,就给
- 实践过程效果代码public partial class Form1 : Form{ public Form1()
- 本文实例讲述了Java日期操作方法工具类。分享给大家供大家参考,具体如下:package com.gcloud.common;import
- 一 前言redis在分布式应用十分广泛,本篇文章也是互联网面试的重点内容,读者至少需要知道为什么需要分布式锁,分布式锁的实现原理,分布式锁的
- 本文实例为大家分享了java实现转圈打印矩阵的具体代码,供大家参考,具体内容如下给定一个整形矩阵Matrix,请按照顺时针方向转圈的方式,输
- 本文的控制台项目是根据SuperSocket官方Telnet示例代码进行调试的,官方示例代码:Telnet示例。开始我的第一个Telnet控
- 事件基于委托,可以为任何一种委托类型提供一种发布\订阅机制。使用event关键字将一个委托类型定义为事件。下面通过一个例子介绍事件://事件
- 本文实例为大家分享了JavaWeb实现注册用户名检测的具体代码,供大家参考,具体内容如下案例说明实现一个可以异步获取用户名是否被注册的小案例
- 概述spirng-aop模块是Spring框架中的核心模块,虽然Spring Ioc container并不依赖AOP,但AOP给Ioc的实
- 1.Fork/Join框架简介Fork/Join 它可以将一个大的任务拆分成多个子任务进行并行处理,最后将子任务结果合并成最后的计算结果,并