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