com.rt.core.util.XSLUtil Maven / Gradle / Ivy
The newest version!
package com.rt.core.util;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import javax.xml.transform.OutputKeys;
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 org.dom4j.DocumentException;
import com.rt.core.constant.RTConst;
class XSLUtil {
/**
* 使用xsl转换xml
*
* @param xslPath
* @param xml
* @return response
* @throws DocumentException
* @throws TransformerException
*/
public static String transformer(URL xslPath, String xml)
throws DocumentException, TransformerException {
// 存储转换完的字符串
StringWriter response = new StringWriter();
// xsl源
Source xslSource = null;
// xml源
Source xmlSource = null;
// 转换器
Transformer transformer = null;
// @see XMLURIResolver
XMLURIResolver xmlURIResolver;
// 构造xml源
xmlSource = new StreamSource(new StringReader(xml));
xmlURIResolver = new XMLURIResolver(xslPath.toString());
TransformerFactory factory = TransformerFactory.newInstance();
factory.setURIResolver(xmlURIResolver);
// 构造xsl源
xslSource = new StreamSource(new StringReader(XMLUtil.readDocument(
xslPath).asXML()));
transformer = factory.newTransformer(xslSource);
// set encoding
transformer.setOutputProperty(OutputKeys.ENCODING, RTConst.UTF_8);
// set method
transformer.setOutputProperty(OutputKeys.METHOD, RTConst.XML);
// do transform
transformer.transform(xmlSource, new StreamResult(response));
return response.toString();
}
}