资讯专栏INFORMATION COLUMN

XML转换

qpwoeiru96 / 2147人阅读

摘要:将转换为字符串将字符串转换为指定类型的指定所有字符串获取节点值测试一中益阳

XmlUtils
package com.daily.xmltest;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class XmlUtils {

    private final static Logger log = Logger.getLogger(XmlUtils.class);

    private static Map>, JAXBContext> jaxbContextMap = new HashMap>, JAXBContext>();
    private static Map>, Unmarshaller> unmarshallerMap = new HashMap>, Unmarshaller>();

    private static XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();

    static {
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, true);
    }

    private static JAXBContext getJaxbInstance(Class... classesToBeBound) throws JAXBException {
        return getJaxbInstance(null, classesToBeBound);
    }

    private static JAXBContext getJaxbInstance(HashSet classes, Class... classesToBeBound) throws JAXBException {
        if (classes == null){
            classes = new HashSet>(CollectionUtils.arrayToList(classesToBeBound));
        }
        JAXBContext jaxbContext = jaxbContextMap.get(classes);
        if (jaxbContext == null){
            jaxbContext = JAXBContext.newInstance(classesToBeBound);
            jaxbContextMap.put(classes, jaxbContext);
        }
        return jaxbContext;
    }

    private static Unmarshaller getUnmarshallerInstance(Class... classesToBeBound) throws JAXBException {
        HashSet classes = new HashSet>(CollectionUtils.arrayToList(classesToBeBound));
        Unmarshaller unmarshaller = unmarshallerMap.get(classes);
        if (unmarshaller == null){
            JAXBContext jaxbContext = getJaxbInstance(classes, classesToBeBound);
            unmarshaller = jaxbContext.createUnmarshaller();
            unmarshallerMap.put(classes, unmarshaller);
        }

        return unmarshaller;
    }

    /**
     * 将javabean转换为XML字符串
     * @param object
     * @return
     */
    public static String convertToXmlStr(Object object, Class... classesToBeBound) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Writer xmlStr = new StringWriter();
        try {
            if (classesToBeBound == null || classesToBeBound.length == 0){
                classesToBeBound = new Class[]{object.getClass()};
            }
            JAXBContext context = getJaxbInstance(classesToBeBound);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
            marshaller.marshal(object, xmlStr);
            stopWatch.stop();
            log.info("Object convert to XML str success, " + xmlStr + ",cost time:" + stopWatch.getTotalTimeMillis() + "ms");
        } catch (JAXBException e) {
            e.printStackTrace();
        } finally {
            if(xmlStr != null) {
                try {
                    xmlStr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return xmlStr.toString().replace("standalone="yes"", "");
    }

    /**
     * 将XML字符串转换为指定类型的javabean
     * @param classesToBeBound 指定所有class
     * @param xmlStr xml字符串
     * @return
     */
    public static Object xmlStrToObject(String xmlStr, Class... classesToBeBound) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object xmlObject = null;
        Reader reader = null;
        XMLStreamReader xmlStreamReader = null;
        try {
            log.info("XML Str convert to Object, xmlStr=" + xmlStr);
            JAXBContext context = getJaxbInstance(classesToBeBound);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            reader = new StringReader(xmlStr);
            xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader);
            xmlObject = unmarshaller.unmarshal(xmlStreamReader);
            stopWatch.stop();
            log.info("XML Str convert to Object success, " + JSON.toJSONString(xmlObject) + ",cost time:" + stopWatch.getTotalTimeMillis() + "ms");
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            if (null != xmlStreamReader){
                try {
                    xmlStreamReader.close();
                } catch (XMLStreamException e) {
                    e.printStackTrace();
                }
            }
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return xmlObject;
    }

    /**
     * 获取节点值
     * @param xmlStr
     * @param nodeName
     * @return
     */
    public static String getNodeValue(String xmlStr, String nodeName){
        if (xmlStr == null) {
            return null;
        }
        int startPos = xmlStr.indexOf("<" + nodeName + ">");
        if (startPos == -1) {
            return null;
        }
        int endPos = xmlStr.lastIndexOf("");
        if (endPos == -1) {
            return null;
        }
        return xmlStr.substring(startPos + ("").length() - 1, endPos);
    }

}
Bean
package com.daily.xmltest.Bean;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.Serializable;

@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="data")
public class School implements Serializable {

    private String schoolName;

    private String address;

    public String getSchoolName() {
        return schoolName;
    }

    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
测试
package com.daily.xmltest;

import com.alibaba.fastjson.JSON;
import com.daily.xmltest.Bean.School;
import org.junit.Test;

public class XMLTest {

    @Test
    public void test() {
        School school = new School();
        school.setSchoolName("一中");
        school.setAddress("益阳");

        String schoolStr = XmlUtils.convertToXmlStr(school);
        System.out.println(schoolStr);

        School parseSchool = (School) XmlUtils.xmlStrToObject(schoolStr, School.class);
        System.out.println(JSON.toJSONString(parseSchool));
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/73827.html

相关文章

  • 分享一个免费的在线表格转换工具 - TableConvert

    摘要:是一个可以在线转换表格的工具,支持表格表格和表格,并且还内嵌了一个表格编辑器,像微软的一样编辑,使用非常方便。拿到对应表格的后,可以直接在文档中使用该文本。 showImg(https://segmentfault.com/img/bVbwJCE?w=1200&h=674); TableConvert 是一个可以在线转换表格的工具,支持 Markdown 表格、CSV、JSON、XML...

    邹强 评论0 收藏0
  • Python: xml转json

    摘要:,实验用的文件我们使用爬虫实战爬取京东商品列表一文的结果文件,爬虫爬取的结果保存在京东手机列表文件中。,相关文档,即时网络爬虫项目内容提取器的定义,爬虫实战爬取京东商品列表,集搜客开源代码下载源,开源网络爬虫源,文档修改历史,首次发布 showImg(https://segmentfault.com/img/bVyf6R); 1,引言 GooSeeker早在9年前就开始了Semanti...

    _Suqin 评论0 收藏0
  • Python: xml转json

    摘要:,实验用的文件我们使用爬虫实战爬取京东商品列表一文的结果文件,爬虫爬取的结果保存在京东手机列表文件中。,相关文档,即时网络爬虫项目内容提取器的定义,爬虫实战爬取京东商品列表,集搜客开源代码下载源,开源网络爬虫源,文档修改历史,首次发布 showImg(https://segmentfault.com/img/bVyf6R); 1,引言 GooSeeker早在9年前就开始了Semanti...

    sourcenode 评论0 收藏0
  • 使用XStream实现Java对象与XML互相转换

    摘要:简介是一个对象与互相转换的工具类库。官网链接简单使用下载页面使用构建项目的加入以下依赖创建对象转使用方法。创建解析对象设置别名默认会输出全路径转为转换后的文本为转对象使用方法。 XStream简介 XStream是一个Java对象与XML互相转换的工具类库。 官网链接: http://x-stream.github.io/index.html 简单使用 下载页面:http://x-st...

    崔晓明 评论0 收藏0
  • JavaScript JavaScript与XML——“XSLT”的注意要点

    摘要:中的它不是一种正式的规范,,是的另一表现形式。是第一个支持它的。主要的功能是用来将转换为文档。方法用于取得当前参数的值,参数为命名空间和参数的内部名称。跨浏览器使用这个函数接收两个参数要执行转换的上下文节点和文档对象。 IE中的XSTL 它不是一种正式的规范,, 是XPath的另一表现形式。 IE是第一个支持它的。 简单的XSTL转换 XML文档的方式就是将它们分别加到一个DOM文档中...

    wupengyu 评论0 收藏0
  • JavaScript JavaScript与XML——“XSLT”的注意要点

    摘要:中的它不是一种正式的规范,,是的另一表现形式。是第一个支持它的。主要的功能是用来将转换为文档。方法用于取得当前参数的值,参数为命名空间和参数的内部名称。跨浏览器使用这个函数接收两个参数要执行转换的上下文节点和文档对象。 IE中的XSTL 它不是一种正式的规范,, 是XPath的另一表现形式。 IE是第一个支持它的。 简单的XSTL转换 XML文档的方式就是将它们分别加到一个DOM文档中...

    LeexMuller 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<