用Stax方式处理xml
1.读取xml文件,首先用类加载器加载项目目录下的xml文件,从XMLInputFactory创建我所需要的XMLStreamReader,即得到了xml文件。根据XMLStreamConstant
属性值,就可以操作所得到的xml文件内容,详情看以下代码。
public class TestStax {
public static void main(String[] args) {
//基于光标式的
// new TestStax().baseStax();
// new TestStax().baseStax_01();
//基于迭代模型的
// new TestStax().baseStax_02();
//基于过滤器的
new TestStax().baseStax_03();
}
public void baseStax(){
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStream is = null;
XMLStreamReader xsr = null;
try {
//第一种加载文件方式,此文件在根目录下
is = TestStax.class.getClassLoader().getResourceAsStream("menu.xml");
xsr = xif.createXMLStreamReader(is);
while(xsr.hasNext()){
int type = xsr.next();
System.out.println(type);
if(type == XMLStreamConstants.START_ELEMENT){
System.out.println(xsr.getName());
}else if(type == XMLStreamConstants.CHARACTERS){
System.out.println(xsr.getText().trim());
}else if(type == XMLStreamConstants.END_ELEMENT){
System.out.println("/" + xsr.getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void baseStax_01(){
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStream is = null;
XMLStreamReader xmlsr = null;
try {
//另一种加载文件方式
is = new FileInputStream(System.getProperty("java.class.path") + File.separator + "menu.xml");
xmlsr = xif.createXMLStreamReader(is);
while(xmlsr.hasNext()){
int type = xmlsr.next();
//XMLStreamConstants.START_ELEMENT=1
if(type == 1){
if("name".equals(xmlsr.getName().toString())){
System.out.print(xmlsr.getElementText() + ":");
}else if("price".equals(xmlsr.getName().toString())){
System.out.println(xmlsr.getElementText());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void baseStax_02(){
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStream is = null;
is = TestStax.class.getClassLoader().getResourceAsStream("menu.xml");
try {
XMLEventReader xmler = xif.createXMLEventReader(is);
while(xmler.hasNext()){
XMLEvent xmle = xmler.nextEvent();
if(xmle.isStartElement()){
String name = xmle.asStartElement().getName().toString();
if("name".equals(name)){
System.out.print(xmler.getElementText() + ":");
}else if("price".equals(name)){
System.out.println(xmler.getElementText());
}
}
}
} catch (XMLStreamException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void baseStax_03(){
XMLInputFactory xif = XMLInputFactory.newFactory();
InputStream is = TestStax.class.getClassLoader().getResourceAsStream("menu.xml");
XMLEventReader xmler = null;
try {
xmler = xif.createFilteredReader(xif.createXMLEventReader(is), new EventFilter() {
@Override
public boolean accept(XMLEvent event) {
if(event.isStartElement()){
String name = event.asStartElement().getName().toString();
if("name".equals(name) || "price".equals(name)){
return true;
}
}
return false;
}
} );
} catch (XMLStreamException e) {
e.printStackTrace();
}
while(xmler.hasNext()){
try {
XMLEvent xmle = xmler.nextEvent();
if(xmle.isStartElement()){
String nm = xmle.asStartElement().getName().toString();
if("name".equals(nm)){
System.out.print(xmler.getElementText() + ":");
}else if("price".equals(nm)){
System.out.println(xmler.getElementText());
}
}
} catch (XMLStreamException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
下面是我说是用的xml,在w3cSchool里弄的xml文件,也可以自己建一个xml文件
<?xml version="1.0" encoding="UTF-8"?> <breakfast_menu>
<food ceshi="test">
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food ceshi="test">
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>
</breakfast_menu>
3.基于Xpath处理xml
//基于Xpath
public void baseStax_04(){
InputStream is = null;
is = TestStax.class.getClassLoader().getResourceAsStream("menu.xml");
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
try {
//创建文档对象
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//创建文档
Document doc = db.parse(is);
NodeList nl = (NodeList)xp.evaluate("//food[@ceshi='test']", doc,XPathConstants.NODESET);
// for(int i=0;i<nl.getLength();i++){
// Element ele = (Element)nl.item(i);
// String value = ele.getElementsByTagName("name").item(0).getTextContent();
// System.out.println(value);
// }
//当不把node转化为element时
for(int j=0;j<nl.getLength();j++){
NodeList nodelist = nl.item(j).getChildNodes();
for(int p=0;p<nodelist.getLength();p++){
Node nodechild = nodelist.item(p);
if(nodechild.getNodeName() != "#text"){
System.out.println(nodechild.getNodeName() + ":" + nodechild.getTextContent());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
4.修改xml,用XPath计算得到查找的位置,修改后用Transformer进行替换原文件
public void update_xml(){
XPath xpath = XPathFactory.newInstance().newXPath();
InputStream is = TestStax.class.getClassLoader().getResourceAsStream("menu.xml");
Document doc= null;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
NodeList nodelist = (NodeList)xpath.evaluate("//food[name='Belgian']", doc,XPathConstants.NODESET );
Element element = (Element)nodelist.item(0);
Element ele = (Element)element.getElementsByTagName("price").item(0);
System.out.println(ele.getTextContent());
ele.setTextContent("12121");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
Result result = new StreamResult(System.out);
transformer.transform(new DOMSource(doc), result);
} catch (Exception e) {
e.printStackTrace();
}
}
5.以XMLStreamWriter的方式写入xml
public void writeXml(){
try {
XMLStreamWriter xmlsw = XMLOutputFactory.newFactory().createXMLStreamWriter(System.out);
xmlsw.writeStartDocument("UTF-8", "1.0");
xmlsw.writeEndDocument();
String ns = "http://xiaoqiaolv";
xmlsw.writeStartElement("ns","student",ns);
xmlsw.writeStartElement("name");
xmlsw.writeAttribute("realname","zhangsan");
xmlsw.writeCharacters("text");
xmlsw.writeEndElement();
xmlsw.writeEndElement();
xmlsw.flush();
xmlsw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
用Stax方式处理xml的更多相关文章
- spring aop注解方式与xml方式配置
注解方式 applicationContext.xml 加入下面配置 <!--Spring Aop 启用自动代理注解 --> <aop:aspectj-autoproxy proxy ...
- iOS 应用数据存储方式(XML属性列表-plist)
iOS 应用数据存储方式(XML属性列表-plist) 一.ios应用常用的数据存储方式 1.plist(XML属性列表归档) 2.偏好设置 3.NSKeydeArchiver归档(存储自定义对象) ...
- iOS开发UI篇—ios应用数据存储方式(XML属性列表-plist)
iOS开发UI篇—ios应用数据存储方式(XML属性列表-plist) 一.ios应用常用的数据存储方式 1.plist(XML属性列表归档) 2.偏好设置 3.NSKeydeArchiver归档(存 ...
- Android网络之数据解析----SAX方式解析XML数据
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...
- 用JAXP的dom方式解析XML文件
用JAXP的dom方式解析XML文件,实现增删改查操作 dom方式解析XML原理 XML文件 <?xml version="1.0" encoding="UTF-8 ...
- Dom方式解析XML
public class TestXML { public static void main(String[] args) throws SAXException, IOException { //D ...
- (四)SAX方式解析XML数据
SAX方式解析XML数据 文章来源:http://www.cnblogs.com/smyhvae/p/4044170.html 一.XML和Json数据的引入: 通常情况下,每个需要访问网络的应用程 ...
- PHP 以POST方式提交XML、获取XML,最后解析XML
以POST方式提交XML // Do a POST $data="<?xml version='1.0' encoding='UTF-8'?> <TypeRsp> & ...
- Struts2第十篇【数据校验、代码方式、XML配置方式、错误信息返回样式】
回顾以前的数据校验 使用一个FormBean对象来封装着web端来过来的数据 维护一个Map集合保存着错误信息-对各个字段进行逻辑判断 //表单提交过来的数据全都是String类型的,birthday ...
随机推荐
- 1activiti认识和数据库和插件配置
工作流介绍 工作流(Workflow),就是通过计算机对业务流程自动化执行管理.它主要解决的是"使在多个参与者之间按照某种预定义的规则自动进行传递文档.信息或任务的过程, 从而实现某个预期的 ...
- iOS Foundation框架 -1.常用结构体的用法和输出
1.安装Xcode工具后会自带开发中常用的框架,存放的地址路径是: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.plat ...
- java-7继承
请自行编写代码测试以下特性(动手动脑):在子类中,若要调用父类中被覆盖的方法,可以使用super关键字. public class QWE { public void main(String[] ...
- InnoDB和Foreign KEY Constraints
InnoDB表中中Foreign Key定义 1. InnoDB允许a foreign key引用一个索引列或者索引组列. 2. InnoDB现在并不支持用户定义的分区表有foreign keys,这 ...
- 如何在 Windows上编译Objective-C
Objective-C现在几乎已经变成了苹果的专利了,可以直接在苹果的Xcode上编译Objective-C程序,但是在Windows平台下的编译工具就寥寥无几了,本身这种语言用的人就不是很多.今天在 ...
- Spring Mvc中使用Task实现定时任务,以及遇到的一个问题
Spring中实现定时任务其实很简单,可以使用spring中自带的task 相当于轻量级的Quartz,并且spring 3.0 之后支持注解的方式,使用起来非常简单,方便,具体实现如下: 第一步,修 ...
- Thrift入门初探(2)--thrift基础知识详解
昨天总结了thrift的安装和入门实例,Thrift入门初探--thrift安装及java入门实例,今天开始总结一下thrift的相关基础知识. Thrift使用一种中间语言IDL,来进行接口的定义, ...
- Web前端浏览器兼容问题
所谓的浏览器兼容性问题,是指因为不同的浏览器对同一段代码有不同的解析,造成页面显示效果不统一的情况.在大多数情况下,我们的需求是,无论用户用什么浏览器来查看我们的网站或者登陆我们的系统,都应该是统一的 ...
- git的安装和环境配置过程(学习笔记)
1.安装git 官网下载:https://github.com(目前官网好像找不到了,但是妙味的视频里面是在官网下载的)https://git-for-windows.github.io/ (廖雪峰老 ...
- c++针对数据库,文件的操作总结(原始)
1.将文件保存到sqlserver数据库的相关操作: Update t1 .txt’, SINGLE_BLOB ) Select convert( varchar(), data ) 注:fileTy ...