用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 ...
随机推荐
- Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSInvocation setArgument:atIndex:]: index (3) out of bounds [-1, 2]'
这是相机调用方法的时候参数错误
- Robot Framework的安装
一.安装环境:Windows 64位操作系统64位2.7版本Python 二.简要步骤:1. 安装Python(RF是基于python 的,所以需要有python环境):2. 安装wxPython ( ...
- C语言一维数组复制
/* * 通过自定义的函数memcpy实现复制功能,优点是不需要引用库函数 * 在windows平台下,通过sizeof测试发现: int 4字节 float 4字节 double 8字节 */ #i ...
- 学习ui-router
ui-router的学习 在单页面应用中要把各个分散的视图给组织起来是通过路由机制来实现的.Angular原始的路由机制靠ngRoute提供,通过hash和history来实现的,可以检测浏览器是否支 ...
- MySQL主从复制的原理和实践操作
MySQL 主从(MySQL Replication),主要用于 MySQL 的实时备份.高可用HA.读写分离.在配置主从复制之前需要先准备 2 台 MySQL 服务器. 一.MySQL主从原理 1. ...
- Codeforce 水题报告
最近做了好多CF的题的说,很多cf的题都很有启发性觉得很有必要总结一下,再加上上次写题解因为太简单被老师骂了,所以这次决定总结一下,也发表一下停课一星期的感想= = Codeforces 261E M ...
- Angular2 Service实践——实现简单音乐播放服务
引言: 如果说组件系统(Component)是ng2应用的躯体,那把服务(Service)认为是流通于组件之间并为其带来生机的血液再合适不过了.组件间通信的其中一种优等选择就是使用服务,在ng1里就有 ...
- 谈 jquery中.band() .live() .delegate() .on()的区别
bind(type,[data],fn) 为每个匹配元素的特定事件绑定事件处理函数 $("a").bind("click",function(){alert(& ...
- 3D Touch开发全面教程之Peek and Pop - 预览和弹出
## 3D Touch开发全面教程之Peek and Pop - 预览和弹出 --- ### 了解3D Touch 在iPhone 6s和iPhone 6s Plus中Apple引入了3D Touch ...
- Python字典详解
转载请注明出处 Python字典(dict)是一个很常用的复合类型,其它常用符合类型有:数组(array).元组(touple)和集合(set).字典是一个key/value的集合,key可以是任意可 ...