浅析DOM4J生成XML,并用DOM4J解析XML

来源:互联网 发布:linux系统jdk1.8下载 编辑:程序博客网 时间:2024/06/09 07:56
package cn.zoo;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.UnsupportedEncodingException;import java.util.Iterator;import java.util.List;import org.dom4j.*;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class ByParseXML {/*** @param args*/public static void main(String[] args)throws Exception {Document doc=DocumentHelper.createDocument();Element root=doc.addElement("modules");root.addAttribute("id","123");Element module=root.addElement("module");module.setText("这是个module标签的文本信息");Element module1=root.addElement("module");module1.addAttribute("id","234");Element name=module1.addElement("name");name.addText("oa");Element value=module1.addElement("value");value.addText("系统基本配置");Element  descript=module1.addElement("descript");Element module2=module1.addElement("mudule");descript.setText("对系统的基本配置根目录");module2.setText("这是个子module标签的文本信息");Element module3=root.addElement("module");Element name2=module3.addElement("name");Element value2=module3.addElement("value");Element descript2=module3.addElement("descript");name2.setText("管理配置");value2.setText("none");descript2.setText("管理配置的说明");Element module4=root.addElement("module");module4.addAttribute("id","106");Element name4=module4.addElement("name");Element value4=module4.addElement("value");Element descript4=module4.addElement("descript");name4.setText("系统管理");value4.setText("0");descript4.setText("Config");Element module5=module4.addElement("module");module5.addAttribute("id", "107");Element name5=module5.addElement("name");Element value5=module5.addElement("value");Element descript5=module5.addElement("descript");name5.setText("部门编号");value5.setText("20394");descript5.setText("编号");OutputFormat format=OutputFormat.createPrettyPrint();format.setEncoding("GBK");XMLWriter xml=new XMLWriter(new FileOutputStream(new File("D:/byParseXML.xml")),format);xml.write(doc);xml.flush();xml.close();SAXReader reader=new SAXReader();Document document=reader.read("D:/byParseXML.xml");Element roo=document.getRootElement();//获取根元素List<Element> elementList=roo.elements();//获取根元素的子元素集合for(Iterator<Element> it=elementList.iterator();it.hasNext();){//遍历子元素Element elem=it.next();List<Element> chil=elem.elements();//子元素又获取子元素的集合for(Iterator<Element> i=chil.iterator();i.hasNext();){//遍历子元素Element chilElem=(Element)i.next();String str=chilElem.getText();//读取每个子元素的内容Iterator a=chilElem.attributeIterator();System.out.println( chilElem.getName()+str);}System.out.println("***************************************");}}}


0 0
原创粉丝点击