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

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(@*) &gt; 0)">
         "<xsl:value-of select="local-name()"/>": <xsl:value-of select="$elementData"/>
        </xsl:if>
        <xsl:if test="count(@*) &gt; 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秒的

你可能感兴趣的:(JavaScript,xml,json,Gmail,XSL)