使用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")); //写文件
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/328253.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

c语言关于计算的函数,问个c语言题目,关于一个计算器的有参有返回函数!!!...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼printf("toM");scanf("%d",&toM);if(toM0)printf("错误&#xff0c;除数不能为0\n");else{resultarith_compliment(toN,toM);printf("\n%d",toN);printf("%%");printf(&quo…

TypeScript 2.0 已发布

微软最近发布了TypeScript 2.0&#xff0c;该版本提供了简化的声明文件获取、Non-nullable类型&#xff0c;以及Readonly修饰符。 TypeScript项目经理Daniel Rosenwasser称&#xff0c;他们团队对于该版本“紧随ECMAScript规范&#xff0c;为JavaScript库和工具提供了更广泛的支…

springboot创建项目2 开发环境的搭建

我也学习了一下 才想着去写个对应的服务器 前端已经全部搭建好了 有很多的坑 你们就不用再次采坑了 我只讲其中的 服务器部分 中间有好多 以后补充吧。。。。

XML解析(二),DOM解析XML

转载自 XML解析&#xff08;二&#xff09;&#xff0c;DOM解析XML上篇文章向大家介绍了SAX解析XML,为了这篇文章理解起来更加方便&#xff0c;所以还没看过SAX解析XML文章的&#xff0c;请戳这【XML解析&#xff08;一&#xff09;】SAX解析XML &#xff0c;这次给大家带来X…

如何通过反射将字符串转换为类

package org.entity; /*** 本案例演示如何通过反射将字符串转换为类* */ public class Test {public static void main(String[] args) {String user "org.entity.User";//字符串是该类的全限定名try {Class clzz Class.forName(user);Object classObjclzz.newInst…

在C语言的函数定义中 如果不需要返回结果,在C语言的函数定义中,如果不需要返回结果,就可以省略return语句...

语言义中语句数定省略保险般来能一几项的职以下说有。来源统计济数据的主要调查得社会经是获&#xff0c;需要包括如下容(的内应该。具体是指&#xff0c;结果积反映房空置面商品&#xff0c;而尚未出屋期末报告工可供销的房出租出租已竣是指售和售或。语言义中语句表现心理学的…

如何将 Microsoft Bot Framework 链接至微信公共号

说到 Microsoft Bot Framework 其实微软发布了已经有一段时间了&#xff0c;有很多朋友可能还不太了解&#xff0c;微软Bot的功能今天我给大家简单的介绍一下&#xff0c;Bot Framework的开发基础以及如何使用Bot Framework和我们的一个现有的三方客服&#xff08;例如一个微信…

XML解析(一),SAX解析XML

转载自 XML解析&#xff08;一&#xff09;&#xff0c;SAX解析XML一、概述SAX&#xff0c;全称Simple API for XML&#xff0c;是一种以事件驱动的XMl API&#xff0c;是XML解析的一种新的替代方法&#xff0c;解析XML常用的还有DOM解析&#xff0c;PULL解析&#xff08;Andr…

go编译库给c语言函数返回值,go语言 函数return值的几种情况

IOS开发基础知识--碎片361:tabBarController跳转到另一个一级页面 当我们用tabBarController时,若已经到其中一个TabBar的子页,又要跳转到某一个一级的页面时,可以这样写 //这样就可以避免跳 ...MapReduce的MapTask任务的运行源码级分析TaskTracker任务初始化及启动task源码级分…

编程语言的发展趋势及未来方向(3):函数式编程

关于声明式编程的还有一部分重要的内容&#xff0c;那便是函数式编程。函数式编程已经有很长时间的历史了&#xff0c;当年LISP便是个函数式编程语言。除了LISP以外我们还有其他许多函数式编程语言&#xff0c;如APL、Haskell、Scheme、ML等等。关于函数式编程在学术界已经有过…

idea中@Data标签getset不起作用

原 idea中Data标签getset不起作用 2017年06月08日 11:22:40 seapeak007 阅读数 27070 spring cloud中使用Data标签&#xff0c;不用手动添加get set方法&#xff0c;但是如果项目中其他类中使用getset方法&#xff0c;如果报错&#xff0c;原因是idea中没有添加Lombok插件&a…

浅析SAX,DOM,JAXP,JDOM与DOM4J之间的关系

转载自 浅析SAX,DOM,JAXP,JDOM与DOM4J之间的关系众所周知&#xff0c;SAX与DOM是JAVA中两大核心XML解析API类库&#xff0c;而JAXP,JDOM与DOM4J都是基于这两大核心API而衍生出来的。今日兴起看了看相关资料&#xff0c;写篇文章总结总结^.^。 SAX与DOM 首先需要说明白的是SAX…

调用反射类的方法

package org.entity;import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;/*** 本案例演示如何通过反射将字符串转换为类* */ public class Test2 {public static void main(String[] args) {String user "org.entity.User";//字…

android 新的布局,Android新布局方式ConstraintLayout快速入门教程

前言在android开发中&#xff0c;我们通常是手写布局&#xff0c;很少会用拖动来写布局&#xff0c;虽然constraintlayout在i/o上以拖动来展现了各种功能&#xff0c;我估计在以后开发中&#xff0c;程序员还是习惯手撸代码。我自己试着拖着用了一下&#xff0c;用得不是很明白…

编程语言的发展趋势及未来方向(2):声明式编程与DSL

这里先从声明式&#xff08;Declarative&#xff09;编程谈起。 目前我们在编写软件时大量使用的是命令式&#xff08;Imperative&#xff09;编程语言&#xff0c;例如C#&#xff0c;Java或是C等等。这些语言的特征在于&#xff0c;写出的代码除了表现出“什么&#xff08;Wha…

HtmlParser提取网页中的纯文本信息

转载自 HtmlParser提取网页中的纯文本信息HTMLParser 一个解析web页面的开源类库。 准备学习下搜索方面的技术&#xff0c;就学习了些网络爬虫的知识。最近一直在一个点上困惑&#xff0c;如何提取一个网页上的纯文本信息。要使用正则表达式的话呢&#xff0c;需要考…

编程语言的发展趋势及未来方向(1):历史回顾及趋势概述

大家好&#xff0c;我是Anders Hejlsberg&#xff0c;现在是微软的Technical Fellow&#xff0c;担任C#编程语言的首席架构师&#xff0c;也参与并领导.NET Framework以及各种语言的开发。我现在打算谈一下……实际上是我脑海中一些影响未来5到10年编程语言设计的内容。比如C#或…

调用反射类的指定方法

package org.entity;import java.lang.reflect.Method;/*** 本案例演示如何通过反射将字符串转换为类* */ public class Test2_2 {public static void main(String[] args) {String user "org.entity.User";//字符串是该类的全限定名try {Class clzz Class.forName…

springboot创建项目 编写dao serviece 和controller 持久层用mybatis

11 刷新一下pom 万一没有引入进去 jpa和mybatis选择哪个&#xff1f; 1.看领导要求 2.都会最好 多学点是没错的