1、Dom4j概述
dom4jis an easy to use,open source library for working with XML,XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM,SAX and JAXP.
dom4j官方网址:dom4j
dom4j源码下载:dom4jdownload
本示例中,需要导入dom4j.jar包,才能引用dom4j相关类,dom4j源码和jar包,请见本示例【源码下载】或访问dom4j
org.dom4j包,不仅包含创建xml的构建器类DocumentHelper、Element,而且还包含解析xml的解析器SAXReader、Element,包含类如下:
org.dom4j
org.dom4j.DocumentHelper;
org.dom4j.Element;
org.dom4j.io.SAXReader;
org.dom4j.io.XMLWriter;
org.dom4j.DocumentException;
sdk源码查看路径(google code)
创建和解析xml的效果图:
2、Dom4j 创建 XML
Dom4j,创建xml主要用到了org.dom4j.DocumentHelper、org.dom4j.Document、org.dom4j.io.OutputFormat、org.dom4j.io.XMLWriter
首先,DocumentHelper.createDocument(),创建org.dom4j.Document 的实例 doc
接着,通过doc,设置xml属性doc.setXMLEncoding("utf-8")、doc.addElement("root")根节点,以及子节点等
然后,定义xml格式并输出,new XMLWriter(xmlWriter,outputFormat)
Code
- /**Dom4j方式,创建XML*/
- publicStringdom4jXMLCreate(){
- StringWriterxmlWriter=newStringWriter();
- Person[]persons=newPerson[3];//创建节点Person对象
- persons[0]=newPerson(1,"sunboy_2050","http://blog.csdn.net/sunboy_2050");
- 1]=newPerson(2,"baidu","http://www.baidu.com");
- 2]=newPerson(3,"google","http://www.google.com");
- try{
- org.dom4j.Documentdoc=DocumentHelper.createDocument();
- doc.setXMLEncoding("utf-8");
- org.dom4j.ElementeleRoot=doc.addElement("root");
- eleRoot.addAttribute("author","homer");
- eleRoot.addAttribute("date","2012-04-25");
- eleRoot.addComment("dom4jtest");
- intpersonsLen=persons.length;
- for(inti=0;i<personsLen;i++){
- ElementelePerson=eleRoot.addElement("person");//创建person节点,引用类为org.dom4j.Element
- ElementeleId=elePerson.addElement("id");
- eleId.addText(persons[i].getId()+"");
- ElementeleName=elePerson.addElement("name");
- eleName.addText(persons[i].getName());
- ElementeleBlog=elePerson.addElement("blog");
- eleBlog.addText(persons[i].getBlog());
- }
- org.dom4j.io.OutputFormatoutputFormat=neworg.dom4j.io.OutputFormat();//设置xml输出格式
- outputFormat.setEncoding("utf-8");
- outputFormat.setIndent(false);
- outputFormat.setNewlines(true);
- outputFormat.setTrimText(true);
- org.dom4j.io.XMLWriteroutput=newXMLWriter(xmlWriter,outputFormat);//保存xml
- output.write(doc);
- output.close();
- }catch(Exceptione){
- e.printStackTrace();
- }
- savedXML(fileName,xmlWriter.toString());
- returnxmlWriter.toString();
- }
运行结果:
3、Dom4j 解析 XML
Dom4j,解析xml主要用到了org.dom4j.io.SAXReader、org.dom4j.Document、doc.getRootElement(),以及ele.getName()、ele.getText()等
首先,创建SAXReader的实例reader,读入xml字节流reader.read(is)
接着,通过doc.getRootElement()得到root根节点,利用迭代器取得root下一级的子节点eleRoot.elementIterator()等
然后,得到解析的xml内容xmlWriter.append(xmlHeader)、xmlWriter.append(personsList.get(i).toString())
解析一:标准解析(Iterator 迭代)
Code