栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 人工智能 > NLP

dom4j 操作xml文件(全)

NLP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

dom4j 操作xml文件(全)

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

我们需要引入的包:

//文件包   import java.io.ByteArrayOutputStream;   import java.io.File;   import java.io.FileWriter;   //工具包   import java.util.Iterator;   import java.util.List;   //dom4j包   import org.dom4j.Attribute;   import org.dom4j.document;   import org.dom4j.documentHelper;   import org.dom4j.Element;   import org.dom4j.io.OutputFormat;   import org.dom4j.io.SAXReader;   import org.dom4j.io.XMLWriter;

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

      public static String doc2String(document document)    {       String s = "";       try       {            //使用输出流来进行转化            ByteArrayOutputStream out = new ByteArrayOutputStream();            //使用GB2312编码            OutputFormat format = new OutputFormat("  ", true, "GB2312");            XMLWriter writer = new XMLWriter(out, format);            writer.write(document);            s = out.toString("GB2312");       }catch(Exception ex)       {                        ex.printStackTrace();       }             return s;    }

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

     public static document string2document(String s)    {       document doc = null;       try       {            doc = documentHelper.parseText(s);       }catch(Exception ex)       {                        ex.printStackTrace();       }       return doc;    }

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

     public static boolean doc2XmlFile(document document,String filename)    {       boolean flag = true;       try       {                          //默认为UTF-8格式,指定为"GB2312"             OutputFormat format = OutputFormat.createPrettyPrint();             format.setEncoding("GB2312");             XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)),format);             writer.write(document);             writer.close();                     }catch(Exception ex)         {             flag = false;             ex.printStackTrace();         }         return flag;          }

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

    public static boolean string2XmlFile(String str,String filename)    {       boolean flag = true;       try       {          document doc =  documentHelper.parseText(str);                 flag = doc2XmlFile(doc,filename);       }catch (Exception ex)       {          flag = false;          ex.printStackTrace();       }       return flag;    }

5、载入一个xml文档

     public static document load(String filename)    {       document document = null;       try        {            SAXReader saxReader = new SAXReader();           document = saxReader.read(new File(filename));       }       catch (Exception ex){           ex.printStackTrace();       }         return document;    }

6、演示String保存为xml文件

     public void xmlWriteDemoByString()    {       String s = "";              s = "rn"          +"   rn"          +"     127.0.0.1rn"          +"     21rn"          +"     cxlrn"          +"     longshinern"          +"     rn"          +"     50rn"          +"     rn"          +"     10rn"          +"  rn"          +"rn";       //将文件生成到classes文件夹所在的目录里          string2XmlFile(s,"xmlWriteDemoByString.xml");          //将文件生成到classes文件夹里          string2XmlFile(s,"classes/xmlWriteDemoByString.xml");      }

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

     public void xmlWriteDemoBydocument()    {                  document document = documentHelper.createdocument();                  Element configElement = document.addElement("config");                  configElement.addComment("东电ftp配置");         Element ftpElement = configElement.addElement("ftp");         ftpElement.addAttribute("name","DongDian");                  Element hostElement = 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");                      doc2XmlFile(document,"classes/xmlWriteDemoBydocument.xml");    }

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

      public static void xmlReadDemo()    {       document doc = load("classes/xmlWriteDemoBydocument.xml");       //Element root = doc.getRootElement();              List list = doc.selectNodes("/config/ftp" );       Iterator it = list.iterator();       while(it.hasNext())       {              Element ftpElement = (Element)it.next();           System.out.println("ftp_name="+ftpElement.attribute("name").getValue());       }              list = doc.selectNodes("/config/ftp/@name" );       it = list.iterator();       while(it.hasNext())       {              Attribute attribute = (Attribute)it.next();           System.out.println("@name="+attribute.getValue());       }              list = doc.selectNodes("/config/ftp/ftp-host" );       it = list.iterator();       Element hostElement=(Element)it.next();       System.out.println("DongDian's ftp_host="+hostElement.getText());    }

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

 ftpElement.remove(hostElement);   ftpElement.remove(nameAttribute);  hostElement.setText("192.168.0.1");   nameAttribute.setValue("ChiFeng");


以上就是 dom4j 操作xml文件(全)的内容,更多相关内容请关注PHP中文网(www.kaotop.com)!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/794922.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号