前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >XMl各种格式转换功能代码

XMl各种格式转换功能代码

作者头像
JQ实验室
发布2022-02-09 15:57:36
4610
发布2022-02-09 15:57:36
举报
文章被收录于专栏:实用技术
代码语言:javascript
复制
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 解析文档

代码语言:javascript
复制
org.dom4j.Element element =  doc.getRootElement();
        
        System.out.println(element.getName());

        
        List<org.dom4j.Element> 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<org.dom4j.Element> 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<org.dom4j.Element> subEl = el.elements();
                        
                        for (org.dom4j.Element e : subEl) {
                            System.out.println(e.getName());
                        }
                    }
                }
                
            }
            
            
        }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-07-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档