基于xsl模板技术把XML转成JSON

本文详细解析了XML到JSON转换的过程,并通过Java代码实现了一个转换工具。介绍了XML到JSON转换的核心原理,包括如何检测数据类型、处理文本、数字、NULL值等,并优化了转换性能,减少了转换时间。通过比较不同技术的性能,展示了优化后的解决方案能显著提升效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XSL摸板 xml-2-json.xml
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:ebl="urn:ebay:apis:eBLBaseComponents" exclude-result-prefixes="ebl">
<!--====================================================================================
Original version by : Holten Norris ( holtennorris at yahoo.com )
Current version maintained by: Alan Lewis (alanlewis at gmail.com)
Thanks to Venu Reddy from eBay XSLT team for help with the array detection code
Protected by CDDL open source license.
Transforms XML into JavaScript objects, using a JSON format.
===================================================================================== -->
<xsl:output method="text" encoding="UTF-8"/>
<xsl:template match="*">
<xsl:param name="recursionCnt">0</xsl:param>
<xsl:param name="isLast">1</xsl:param>
<xsl:param name="inArray">0</xsl:param>
<xsl:if test="$recursionCnt=0">
<xsl:text>json = {</xsl:text>
</xsl:if>
<!-- test what type of data to output -->
<xsl:variable name="elementDataType">
<xsl:value-of select="number(text())"/>
</xsl:variable>
<xsl:variable name="elementData">
<!-- TEXT ( use quotes ) -->
<xsl:if test="string($elementDataType) ='NaN'">
<xsl:if test="boolean(text())">
<xsl:if test="not(*)">
"<xsl:value-of select="text()"/>"
</xsl:if>
</xsl:if>
</xsl:if>
<!-- NUMBER (no quotes ) -->
<xsl:if test="string($elementDataType) !='NaN'">
<xsl:value-of select="text()"/>
</xsl:if>
<!-- NULL -->
<xsl:if test="not(*)">
<xsl:if test="not(text())">
null
</xsl:if>
</xsl:if>
</xsl:variable>
<xsl:variable name="hasRepeatElements">
<xsl:for-each select="*">
<xsl:if test="name() = name(preceding-sibling::*) or name() = name(following-sibling::*)">
true
</xsl:if>
</xsl:for-each>
</xsl:variable>
<xsl:if test="not(count(@*) > 0)">
"<xsl:value-of select="local-name()"/>": <xsl:value-of select="$elementData"/>
</xsl:if>
<xsl:if test="count(@*) > 0">
"<xsl:value-of select="local-name()"/>": {
"content": <xsl:value-of select="$elementData"/>
<xsl:for-each select="@*">
<xsl:if test="position()=1">,</xsl:if>
<!-- test what type of data to output -->
<xsl:variable name="dataType">
<xsl:value-of select="number(.)"/>
</xsl:variable>
<xsl:variable name="data">
<!-- TEXT ( use quotes ) -->
<xsl:if test="string($dataType) ='NaN'">
"<xsl:value-of select="current()"/>" </xsl:if>
<!-- NUMBER (no quotes ) -->
<xsl:if test="string($dataType) !='NaN'">
<xsl:value-of select="current()"/>
</xsl:if>
</xsl:variable>
<xsl:value-of select="local-name()"/>:<xsl:value-of select="$data"/>
<xsl:if test="position() !=last()">, </xsl:if>
</xsl:for-each>
}
</xsl:if>
<xsl:if test="not($hasRepeatElements = '')">
[{
</xsl:if>
<xsl:for-each select="*">
<xsl:if test="position()=1">
<xsl:if test="$hasRepeatElements = ''">
<xsl:text> { </xsl:text>
</xsl:if>
</xsl:if>
<xsl:apply-templates select="current()">
<xsl:with-param name="recursionCnt" select="$recursionCnt+1"/>
<xsl:with-param name="isLast" select="position()=last()"/>
<xsl:with-param name="inArray" select="not($hasRepeatElements = '')"/>
</xsl:apply-templates>
<xsl:if test="position()=last()">
<xsl:if test="$hasRepeatElements = ''">
<xsl:text> } </xsl:text>
</xsl:if>
</xsl:if>
</xsl:for-each>
<xsl:if test="not($hasRepeatElements = '')">
}]
</xsl:if>
<xsl:if test="not( $isLast )">
<xsl:if test="$inArray = 'true'">
<xsl:text> } </xsl:text>
</xsl:if>
,
<xsl:if test="$inArray = 'true'">
<xsl:text> { </xsl:text>
</xsl:if>
</xsl:if>
<xsl:if test="$recursionCnt=0"> }; </xsl:if>
</xsl:template>
</xsl:stylesheet>


JAVA代码
public class XmlJson {
public static String process(String resrouce, String xslFile) {
URL oUrl = XmlJson.class.getResource("/");
File oFileurl = new File(oUrl.getFile());
xslFile = oFileurl.getAbsolutePath() +"\\"+ xslFile;
StringWriter out = new StringWriter();
try {
TransformerFactory transFactory = TransformerFactory.newInstance();
StreamSource streamSourcexslt = new StreamSource(xslFile);
StreamSource streamSourcexml = new StreamSource(new StringReader(
resrouce));
Transformer xsltTransformer = transFactory
.newTransformer(streamSourcexslt);
xsltTransformer.transform(streamSourcexml, new StreamResult(out));
} catch (TransformerConfigurationException tce) {
System.out.println("ERROR: TransformerConfigurationException "
+ tce);
tce.printStackTrace();

} catch (TransformerException te) {
System.out.println("ERROR: TransformerException " + te);
te.printStackTrace();

}

return out.toString();
}

public static String open(String url, String s) {
URL oUrl = XmlJson.class.getResource("/");
File oFileurl = new File(oUrl.getFile());
url = oFileurl.getAbsolutePath()+"\\" + url;
Document oDocument = null;
if (url.length() > 0) {
SAXReader reader = new SAXReader();
try {
oDocument = reader.read(url);

} catch (DocumentException e) {
try {
if (null != s) {
if (s.length() > 0) {
oDocument = DocumentHelper.parseText(s);
}
}
File oFile = new File(url);
url = oFile.getParent();
if (null != url)
oFile = new File(url);
oFile.mkdirs();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
return oDocument.asXML();
}
public static void main(String[] args){
String xml=XmlJson.open("rsp.xml","<rsp/>");

// long end=System.currentTimeMillis()-begin;
System.out.println(XmlJson.process(xml, "xml-2-json.xml"));

}
}

改技术性能比较差,100次需要7秒.用json-lib直接用对象转成xml会比较快,1W次0.7秒的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值