xslt转换xml

时间:2021-06-29 10:54:42

实现json--> xml --(xlst)--> xml

pom依赖

        <dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>xom</groupId>
<artifactId>xom</artifactId>
<version>1.2.5</version>
</dependency>

转换规则xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" cdata-section-elements="title artist"/>
<!-- match the document root -->
<xsl:template match="/">
<package>
<xsl:for-each select="o/package">
<title><xsl:value-of select="abstract"/></title>
<artist><xsl:value-of select="source"/></artist>
</xsl:for-each>
</package>
</xsl:template>
</xsl:stylesheet>

java代码

package com.test.main;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException; import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource; import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer; public class TestMain {
public static void main(String[] args) throws IOException, URISyntaxException, TransformerException {
// String jsonString ="{'package':{'abstract':'<![CDATA[<Empire <>Burlesque>]]>','source':'<![CDATA[Bob Dylan]]>'}}";
String jsonString ="{'package':{'abstract':'<<>>??<Empire <>Burlesque>','source':'<![CDATA[Bob Dylan]]>'}}";
XMLSerializer xmlSerializer = new XMLSerializer();
String str = xmlSerializer.write(JSONSerializer.toJSON(jsonString));
byte[] xml = str.getBytes();
File name = new File("D:\\tt\\xslt\\source_22.xml");
FileOutputStream os = new FileOutputStream(name);
os.write(xml); TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(new File("D:/tt/xslt/modul_11.xslt"));
Transformer transformer = factory.newTransformer(xslt); Source text = new StreamSource(name);
transformer.transform(text, new StreamResult(new File("D:/tt/xslt/result/output_11.xml")));
}
}