Java操作XML文件 dom4j 篇

在项目中,我们很多都用到了xml文件,无论是参数配置还是与其它系统的数据交互。今天就来讲一下Java 中使用dom4j来操作XML文件。

我们需要引入的包:

//文件包importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileWriter;//工具包importjava.util.Iterator;importjava.util.List;//dom4j包importorg.dom4j.Attribute;importorg.dom4j.Document;importorg.dom4j.DocumentHelper;importorg.dom4j.Element;importorg.dom4j.io.OutputFormat;importorg.dom4j.io.SAXReader;importorg.dom4j.io.XMLWriter;

1、将XML文件的内容转化为String

/***doc2String*将xml文档内容转为String*@return字符串*@paramdocument*/publicstaticStringdoc2String(Documentdocument){Strings="";try{//使用输出流来进行转化ByteArrayOutputStreamout=newByteArrayOutputStream();//使用GB2312编码OutputFormatformat=newOutputFormat("",true,"GB2312");XMLWriterwriter=newXMLWriter(out,format);writer.write(document);s=out.toString("GB2312");}catch(Exceptionex){ex.printStackTrace();}returns;}

2、将符合XML格式的String 转化为XML Document

/***string2Document*将字符串转为Document*@return*@paramsxml格式的字符串*/publicstaticDocumentstring2Document(Strings){Documentdoc=null;try{doc=DocumentHelper.parseText(s);}catch(Exceptionex){ex.printStackTrace();}returndoc;}

3、将Document对象保存为一个xml文件到本地

/***doc2XmlFile*将Document对象保存为一个xml文件到本地*@returntrue:保存成功flase:失败*@paramfilename保存的文件名*@paramdocument需要保存的document对象*/publicstaticbooleandoc2XmlFile(Documentdocument,Stringfilename){booleanflag=true;try{/*将document中的内容写入文件中*///默认为UTF-8格式,指定为"GB2312"OutputFormatformat=OutputFormat.createPrettyPrint();format.setEncoding("GB2312");XMLWriterwriter=newXMLWriter(newFileWriter(newFile(filename)),format);writer.write(document);writer.close();}catch(Exceptionex){flag=false;ex.printStackTrace();}returnflag;}

4、将xml格式的字符串保存为本地文件,如果字符串格式不符合xml规则,则返回失败

/***string2XmlFile*将xml格式的字符串保存为本地文件,如果字符串格式不符合xml规则,则返回失败*@returntrue:保存成功flase:失败*@paramfilename保存的文件名*@paramstr需要保存的字符串*/publicstaticbooleanstring2XmlFile(Stringstr,Stringfilename){booleanflag=true;try{Documentdoc=DocumentHelper.parseText(str);flag=doc2XmlFile(doc,filename);}catch(Exceptionex){flag=false;ex.printStackTrace();}returnflag;}

5、载入一个xml文档

/***load*载入一个xml文档*@return成功返回Document对象,失败返回null*@paramuri文件路径*/publicstaticDocumentload(Stringfilename){Documentdocument=null;try{SAXReadersaxReader=newSAXReader();document=saxReader.read(newFile(filename));}catch(Exceptionex){ex.printStackTrace();}returndocument;}

6、演示String保存为xml文件

/***xmlWriteDemoByString*演示String保存为xml文件*/publicvoidxmlWriteDemoByString(){Strings="";/**xml格式标题"<?xmlversion=’1.0’encoding=’GB2312′?>"可以不用写*/s="<config>\r\n"+"<ftpname=’DongDian’>\r\n"+"<ftp-host>127.0.0.1</ftp-host>\r\n"+"<ftp-port>21</ftp-port>\r\n"+"<ftp-user>cxl</ftp-user>\r\n"+"<ftp-pwd>longshine</ftp-pwd>\r\n"+"<!–ftp最多尝试连接次数–>\r\n"+"<ftp-try>50</ftp-try>\r\n"+"<!–ftp尝试连接延迟时间–>\r\n"+"<ftp-delay>10</ftp-delay>\r\n"+"</ftp>\r\n"+"</config>\r\n";//将文件生成到classes文件夹所在的目录里string2XmlFile(s,"xmlWriteDemoByString.xml");//将文件生成到classes文件夹里string2XmlFile(s,"classes/xmlWriteDemoByString.xml");}

7、演示手动创建一个Document,并保存为XML文件

/***演示手动创建一个Document,并保存为XML文件*/publicvoidxmlWriteDemoByDocument(){/**建立document对象*/Documentdocument=DocumentHelper.createDocument();/**建立config根节点*/ElementconfigElement=document.addElement("config");/**建立ftp节点*/configElement.addComment("东电ftp配置");ElementftpElement=configElement.addElement("ftp");ftpElement.addAttribute("name","DongDian");/**ftp属性配置*/ElementhostElement=ftpElement.addElement("ftp-host");hostElement.setText("127.0.0.1");(ftpElement.addElement("ftp-port")).setText("21");(ftpElement.addElement("ftp-user")).setText("cxl");(ftpElement.addElement("ftp-pwd")).setText("longshine");ftpElement.addComment("ftp最多尝试连接次数");(ftpElement.addElement("ftp-try")).setText("50");ftpElement.addComment("ftp尝试连接延迟时间");(ftpElement.addElement("ftp-delay")).setText("10");/**保存Document*/doc2XmlFile(document,"classes/xmlWriteDemoByDocument.xml");}

8、演示读取文件的具体某个节点的值

/***演示读取文件的具体某个节点的值*/publicstaticvoidxmlReadDemo(){Documentdoc=load("classes/xmlWriteDemoByDocument.xml");//Elementroot=doc.getRootElement();/**先用xpath查找所有ftp节点并输出它的name属性值*/Listlist=doc.selectNodes("/config/ftp");Iteratorit=list.iterator();while(it.hasNext()){ElementftpElement=(Element)it.next();System.out.println("ftp_name="+ftpElement.attribute("name").getValue());}/**直接用属性path取得name值*/list=doc.selectNodes("/config/ftp/@name");it=list.iterator();while(it.hasNext()){Attributeattribute=(Attribute)it.next();System.out.println("@name="+attribute.getValue());}/**直接取得DongDianftp的ftp-host的值*/list=doc.selectNodes("/config/ftp/ftp-host");it=list.iterator();ElementhostElement=(Element)it.next();System.out.println("DongDian’sftp_host="+hostElement.getText());}

9、修改或删除某个值或属性

/**ftp节点删除ftp-host节点*/ftpElement.remove(hostElement);/**ftp节点删除name属性*/ftpElement.remove(nameAttribute);/**修改ftp-host的值*/hostElement.setText("192.168.0.1");/**修改ftp节点name属性的值*/nameAttribute.setValue("ChiFeng");想做你的有缘人,可是我知道结果是惨淡的,但还是心存希望!

Java操作XML文件 dom4j 篇

相关文章:

你感兴趣的文章:

标签云: