使用JDOM2.0.4 操作/解析xml
转载自 使用JDOM2.0.4 操作/解析xml
一、解析xml内容
xml文件内容:
<?xml version="1.0" encoding="utf-8"?> <RETVAL success='true'> <Shop><sid>1</sid><name>北京鑫和易通贸易有限公司</name></Shop> <Shop><sid>2</sid><name>张家口市金九福汽车服务有限公司</name></Shop> </RETVAL>
解析的java代码
import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.xml.sax.InputSource;public Class Test{public static List test() throws Exception{List result = new ArrayList();SAXBuilder builder = new SAXBuilder();StringReader read = new StringReader(xmlDoc);InputSource source = new InputSource(read);Document document = builder.build(source);Element root = document.getRootElement();// 获得根节点String ifSuccess = root.getAttributeValue("success");if (!"true".equals(ifSuccess)) {// 不成功直接返回throw new Exception("从接口获取全部经销商数据时不成功!");}List<Element> childrenList = root.getChildren();for (Element e : childrenList) {Map elementMap = new HashMap<String, String>();elementMap.put("sid", e.getChildText("sid")); // 经销商idelementMap.put("name", e.getChildText("name")); // 经销商名称 result.add(elementMap);}return result;} }
二、解析和操作xml文件
xml文件内容
<?xml version="1.0" encoding="UTF-8"?> <root><person id="1"><username>张三</username><password>123123</password></person><person id="2"><username>1111111112</username><password>password2</password></person> </root>
JDOM构建document对象的方法
Document build(java.io.File file) //This builds a document from the supplied filename. Document build(org.xml.sax.InputSource in) //This builds a document from the supplied input source. Document build(java.io.InputStream in) //This builds a document from the supplied input stream. Document build(java.io.InputStream in, java.lang.String systemId) //This builds a document from the supplied input stream. Document build(java.io.Reader characterStream) //This builds a document from the supplied Reader. Document build(java.io.Reader characterStream, java.lang.String systemId) //This builds a document from the supplied Reader. Document build(java.lang.String systemId) //This builds a document from the supplied URI. Document build(java.net.URL url) //This builds a document from the supplied URL.
解析、新增、修改、删除xml节点属性的java
package test;import java.io.FileWriter; import java.util.List;import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter;public class Test {/*** @param args* @throws Exception */public static void main(String[] args) throws Exception {SAXBuilder builder = new SAXBuilder();//Document doc = builder.build(new File("src/test.xml"));//Document doc = builder.build(new FileInputStream("src/test.xml"));//Document doc = builder.build(new FileReader("src/test.xml"));//Document doc = builder.build(new URL("http://localhost:8080/jdomTest/test.xml"));Document doc = builder.build("src/test.xml");//readXmlFile(doc);//addXmlElement(doc);//updateXmlElement(doc); deleteXmlElement(doc);}/*** 解析xml文件* @throws Exception*/public static void readXmlFile(Document doc) throws Exception {Element root = doc.getRootElement(); //获取根元素 System.out.println("---获取第一个子节点和子节点下面的节点信息------");Element e = root.getChild("person"); //获取第一个子元素System.out.println("person的属性id的值:"+e.getAttributeValue("id")); //获取person的属性值for(Element el: e.getChildren()){System.out.println(el.getText());//第一次输入张三 第二次输出123123System.out.println(el.getChildText("username"));//这里这么写会是nullSystem.out.println(el.getChildText("password"));//这里这么写会是null }System.out.println("---直接在根节点下就遍历所有的子节点---");for(Element el: root.getChildren()){System.out.println(el.getText());//这里输出4行空格System.out.println(el.getChildText("username"));//输出张三 & 1111111112System.out.println(el.getChildText("password"));//输出123123 & password2 }}/*** 新增节点* @throws Exception*/public static void addXmlElement(Document doc) throws Exception {Element root = doc.getRootElement(); //获取根元素 Element newEle = new Element("person");//设置新增的person的信息newEle.setAttribute("id","88888");Element chiledEle = new Element("username"); //设置username的信息chiledEle.setText("addUser");newEle.addContent(chiledEle);Element chiledEle2 = new Element("password"); //设置password的信息chiledEle2.setText("addPassword");newEle.addContent(chiledEle2);root.addContent(newEle);XMLOutputter out = new XMLOutputter();out.setFormat(Format.getCompactFormat().setEncoding("GBK"));//设置UTF-8编码,理论上来说应该不会有乱码,但是出现了乱码,故设置为GBKout.output(doc, new FileWriter("src/test.xml")); //写文件 }/*** 更新节点* @param doc* @throws Exception*/public static void updateXmlElement(Document doc) throws Exception {Element root = doc.getRootElement(); //获取根元素//循环person元素并修改其id属性的值for(Element el : root.getChildren("person")){el.setAttribute("id","haha");}//循环设置username和password的文本值和添加属性for(Element el: root.getChildren()){el.getChild("username").setAttribute("nameVal", "add_val").setText("update_text"); el.getChild("password").setAttribute("passVal", "add_val").setText("update_text"); }XMLOutputter out = new XMLOutputter();out.setFormat(Format.getCompactFormat().setEncoding("GBK"));//设置UTF-8编码,理论上来说应该不会有乱码,但是出现了乱码,故设置为GBKout.output(doc, new FileWriter("src/test.xml")); //写文件 }/*** 删除节点和属性* @param doc* @throws Exception*/public static void deleteXmlElement(Document doc) throws Exception {Element root = doc.getRootElement(); //获取根元素 List<Element> personList = root.getChildren("person");//循环person元素,删除person的id为1的id属性以及username子节点for(Element el : personList){if(null!=el.getAttribute("id") && "1".equals(el.getAttribute("id").getValue())){el.removeAttribute("id");el.removeChild("username");}}//循环person元素,删除person的id为2的节点for(int i=0; i<personList.size(); i++){Element el = personList.get(i);if(null!=el.getAttribute("id") && "2".equals(el.getAttribute("id").getValue())){root.removeContent(el);//从root节点上删除该节点//警告:此处删除了节点可能会使personList的长度发生变化而发生越界错误,故不能写成for(int i=0,len=personList.size(); i<len; i++) }}XMLOutputter out = new XMLOutputter();out.setFormat(Format.getCompactFormat().setEncoding("GBK"));//设置UTF-8编码,理论上来说应该不会有乱码,但是出现了乱码,故设置为GBKout.output(doc, new FileWriter("src/test.xml")); //写文件 } }
使用JDOM2.0.4 操作/解析xml相关推荐
- cocos2d-x 3.0 使用Sax解析xml文档(解决中文显示问题)
今天是个好日子,心想的事儿都能成,明天是个好日子,打开了家门儿迎春风... 恩,听着歌写文档生活就是这么享受. 今天以前的邻居大神突然在qq上赞了我一下,这让我异常激动啊..这还要从前前前几天说起,那 ...
- java stax xml_在JDK6.0中用StAX解析XML
摘要 J2EE/XML开发人员一般都用DOM(Document Object Model,文档对象模型)API或者(SAX Simple API for XML)来解析XML文件.这些API各有利弊. ...
- Java JDOM生成和解析XML
一)JDOM介绍 使用方式:需要下载jdom对应的jar引入 <dependency><groupId>org.jdom</groupId><artifact ...
- 使用bash解析xml
最初的需求是希望bash能提供完整成熟的xml解析工具来解析xml,但是并没有找到这样的工具.后来在StackOverFlow上找到一个简单的处理xml的方法,即: rdom () { local I ...
- java使用org.w3c.dom解析XML文档,创建、增删查改,保存,读取,遍历元素等操作
全栈工程师开发手册 (作者:栾鹏) java教程全解 java使用org.w3c.dom(java dom)解析XML文档,创建.增删查改,保存,读取,遍历元素等操作 在保存文件时需要载入crimso ...
- MySQL存储过程 — 解析 XML 数据并实现插入操作
MySQL存储过程 - 解析 XML 数据并实现插入操作 一.概述: 最近在做项目的过程中,需要利用MySQL存储过程 解析 XML数据并进行插入操作,因此就学习了下.MySQL 解析 XML 的思路 ...
- tinyxml2 数组_7.数据本地化CCString,CCArray,CCDictionary,tinyxml2,写入UserDefault.xml文件,操作xml,解析xml...
数据本地化 A CCUserDefault 系统会在默认路径cocos2d-x-2.2.3\projects\Hello\proj.win32\Debug.win32下生成一个名为UserDef ...
- C++中XML的读写操作(生成XML 解析XML)
一.用Poco库 Poco库是下载.编译和使用:www.cnblogs.com/htj10/p/11380144.html DOM(The Document Object Model)方式: 1. 生 ...
- php xml expat,php 使用expat方式解析xml文件操作示例
本文实例讲述了php 使用expat方式解析xml文件操作.分享给大家供大家参考,具体如下: test.xml: George John Reminder George2 John2 Reminder ...
最新文章
- c++ char数组初始化_c专题指针数组与指针的关联
- 调查:中国CIO在亚太拥最大战略影响力
- SQL Server 数据库状态选项
- windows XP和ubuntu时间一致
- pythonturtle是标准库_Python标准库: turtle--海龟绘图。
- iphone开发每日一练【2011-10-04】
- FileZilla Server + FlashFXP 快速搭建FTP服务
- 三相电机控制方式入门,看完这一篇就够了
- 4python小项目---# 体脂率计算
- 教你通过bigemap和geojson获取echarts精确到乡镇、街道的地图json数据
- Bug随手记----关于java.lang.IllegalStateException: The following classes could not be excluded because the
- 显示器测试程序(黑、白、红、绿、蓝)--C++实现(MFC)
- 蜡烛图(K线图)-2反转形态
- python文件打开模式的合法组合,python文件操作
- 他,生物系毕业,刚入职连Java都没听过,却在马云的要求下,三周写出淘宝网雏形...
- 基于PageRank的复杂网络社区发现
- 中移动全球通新套餐话费时长缩水
- oracle 跨平台adg,oracle ADG 跨版本跨平台搭建实测
- “10类”电子劳动合同签署工具:节约时间、高效签署
- 分享一个超级玛丽源码
热门文章
- C++中getline()和cin()同时使用时的注意事项
- 7-21 求前缀表达式的值 (25 分)(思路详解)
- [Spring5]IOC容器_Bean管理XML方式_自动装配
- [PAT乙级]1019 数字黑洞
- 算法导论水壶问题(第三版第八章思考题8-4)
- 2019-03-10-算法-进化(只出现一次的数字)
- HDU - 6959 zoto 莫队 + 值域分块
- Recursive sequence HDU - 5950
- 【每日一题】7月14日题目精讲—压缩
- AtCoder3950 [AGC022E] Median Replace(DFA + dp)