博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
XMl各种格式转换功能代码
阅读量:6604 次
发布时间:2019-06-24

本文共 7416 字,大约阅读时间需要 24 分钟。

package com.cdv.test;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.StringReader;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Result;import javax.xml.transform.Source;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;import org.jdom2.input.SAXBuilder;import org.jdom2.output.Format;import org.jdom2.output.XMLOutputter;import org.w3c.dom.Document;import org.xml.sax.InputSource;public class XmlKit {    /**     * dom4j解析xml     */        public static org.dom4j.Document xmlTodDocDom4j(String path){        File file = new File(path);        org.dom4j.Document doc = null;        try {             doc = new SAXReader().read(file);        } catch (DocumentException e) {            e.printStackTrace();        }        return doc;    }        public static String docToString(org.dom4j.Document document){        String xmlStr = document.asXML();        return xmlStr;    }        public static org.dom4j.Document stringToXmlDom4j(String xmlStr){                        org.dom4j.Document doc = null;        try {            doc = DocumentHelper.parseText(xmlStr);        } catch (DocumentException e) {            e.printStackTrace();        }        return doc;    }         /**      * Document 保存为 XML 文件      *       * @param doc Document对象      * @param path 文件路径      */      public static void doc2XMLDom4j(org.dom4j.Document doc, String path) {          try {              XMLWriter xmlWriter = new XMLWriter(new FileWriter(path));            xmlWriter.write(doc);            xmlWriter.flush();              xmlWriter.close();          } catch (Exception e) {              return;          }      }              /**     * jdom解析xml     */        public static org.jdom2.Document xmlTodDocJdom(String path){        File file = new File(path);        org.jdom2.Document doc = null;        try {             doc =new SAXBuilder().build(file);        } catch (Exception e) {            e.printStackTrace();        }        return doc;    }    public static String docToString(org.jdom2.Document doc){                String xmlStr = "";        Format format = Format.getPrettyFormat();              format.setEncoding("UTF-8");//配置xml文档的字符为gb2312,解决中文问题              XMLOutputter xmlout = new XMLOutputter(format);             ByteArrayOutputStream bo = new ByteArrayOutputStream();             try {            xmlout.output(doc,bo);        } catch (IOException e) {            e.printStackTrace();        }              xmlStr = bo.toString();        return xmlStr;    }        public static org.jdom2.Document stringTodDocJdom (String xmlStr){            org.jdom2.Document doc = null;            StringReader sr = new StringReader(xmlStr);                 InputSource is = new InputSource(sr);                 try {                doc =(new SAXBuilder()).build(is);            } catch (Exception e) {                e.printStackTrace();            }                  return doc;    }     /**      * DOCUMENT格式化输出保存为XML      *       * @param doc JDOM的Document      * @param filePath 输出文件路径      * @throws Exception      */      public static void doc2XML(org.jdom2.Document doc, String filePath) throws Exception{          Format format = Format.getCompactFormat();           format.setEncoding("UTF-8"); //设置XML文件的字符为UTF-8          format.setIndent("     ");//设置缩进           XMLOutputter outputter = new XMLOutputter(format);//定义输出 ,在元素后换行,每一层元素缩排四格           FileWriter writer = new FileWriter(filePath);//输出流          outputter.output(doc, writer);          writer.close();      }              /**     * jdk api解析xml     */        public static Document xmlTodDoc(String path){        File file = new File(path);        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();          DocumentBuilder builder = null;          Document doc = null;        try {            builder = factory.newDocumentBuilder();            doc = builder.parse(file);        } catch (Exception e) {            e.printStackTrace();        }        return doc;    }        public static String xmlToString(Document doc){                    String xmlStr = "";            TransformerFactory  tf  =  TransformerFactory.newInstance();                Transformer t;            try {                t = tf.newTransformer();                ByteArrayOutputStream  bos  =  new  ByteArrayOutputStream();                   t.transform(new DOMSource(doc), new StreamResult(bos));                    xmlStr = bos.toString();                } catch (Exception e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            return xmlStr;    }        public static Document stringToXml(String xmlStr){            Document doc = null;            StringReader sr = new StringReader(xmlStr);               InputSource is = new InputSource(sr);               DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();               DocumentBuilder builder;            try {                builder = factory.newDocumentBuilder();                doc = builder.parse(is);              } catch (Exception e) {                e.printStackTrace();            }                     return doc;    }         /**      * Document 保存为 XML 文件      *       * @param doc Document对象      * @param path 文件路径      */      public static void doc2XML(Document doc, String path) {          try {              Source source = new DOMSource(doc);              Result result = new StreamResult(new File(path));              Transformer transformer = TransformerFactory.newInstance().newTransformer();              transformer.setOutputProperty(OutputKeys.INDENT, "yes");              transformer.transform(source, result);          } catch (Exception e) {              return;          }      }      }

 dom4J 解析文档

org.dom4j.Element element =  doc.getRootElement();                System.out.println(element.getName());                List
iter = element.elements(); for (org.dom4j.Element elem : iter) { System.out.println(elem.getName()); if(elem.getName().equals("HeadInfo")){ System.out.println(elem.attributeValue("PGMVersion")); }; if(elem.getName().equals("PGM")){ List
subIter = elem.elements(); for (org.dom4j.Element el : subIter) { System.out.println(el.getName()); System.out.println(el.attributeValue("ItemType")); if(el.attributeValue("ItemType").equals("1")){ List
subEl = el.elements(); for (org.dom4j.Element e : subEl) { System.out.println(e.getName()); } } } } }

 

转载于:https://www.cnblogs.com/liangblog/p/4667522.html

你可能感兴趣的文章
JS模拟select下拉菜单
查看>>
线性方程组迭代求解——Jacobi迭代算法(Python实现)
查看>>
vmware workstation14永久激活密钥分享
查看>>
PHP面向对象的进阶学习(抽像类、接口、final、类常量)
查看>>
iOS 多线程 之 GCD(大中枢派发)(一)
查看>>
pstool 的使用方法
查看>>
mysql用户与权限管理笔记
查看>>
a里面不能嵌套a
查看>>
Myeclipse中打开接口实现类的快捷键
查看>>
浅谈React数据流管理
查看>>
<20190516> 一次比较糟糕的售后维修体验(某硕主板)
查看>>
iOS网络篇2-http协议通信规则
查看>>
删除sql dump中的AUTO_INCREMENT
查看>>
使用JdbcTemplate和JdbcDaoSupport
查看>>
C博客作业--指针
查看>>
版本12.2.0.1.0数据库,复制种子数据库快速创建租户数据库PDB
查看>>
吴忠军中华演出网
查看>>
Page翻页分页css代码,分页div+css代码
查看>>
编程之美 第1章 游戏之乐——游戏中碰到的题目(十一)
查看>>
mysql for Mac 下创建数据表中文显示为?的解决方法
查看>>