在java中解析xslt的代码

五月 15th, 2010 by 寻道者


通常情况下,我们都使用xslt来解析xml文件,然后生成网页。在C#中有自带的xml控件,可以指定xml与xslt就能输出了,而在java,这一步要自己实现,以下是实现的代码,最终生成html代码,并取第38个字符以后的所有内容,主要是去掉了xml声明头。

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/**
 * Xslt解析
 *
 * @author ywx
 */
public class Xslt
{
	/**
	 * xslt转换 重载+1
	 *
	 * @param xmlfilename
	 *            xml文件路径
	 * @param xsltfilename
	 *            xslt文件路径
	 * @return 返回转换后的字符串
	 * @throws TransformerFactoryConfigurationError
	 * @throws TransformerException
	 */
	public static String Transform(String xmlfilename, String xsltfilename) throws TransformerFactoryConfigurationError, TransformerException
	{
		File styleSheet = new File(xsltfilename);
		StreamSource styleSource = new StreamSource(styleSheet);
		Transformer t = TransformerFactory.newInstance().newTransformer(styleSource);
		File file = new File(xmlfilename);
		StringWriter w = new StringWriter();
		StreamResult result = new StreamResult(w);
		try
		{
			t.transform(new StreamSource(file), result);
			w.close();
		}
		catch (TransformerException e)
		{
		}
		catch (IOException e)
		{
		}
		return w.toString().substring(39);
	}
	/**
	 * xslt转换 重载+1
	 *
	 * @param _node
	 *            xml文档节点
	 * @param xsltfilename
	 *            xslt文件路径
	 * @return 返回转换后的字符串
	 * @throws TransformerFactoryConfigurationError
	 * @throws TransformerException
	 */
	public static String Transform(XmlNode _node, String xsltfilename) throws TransformerFactoryConfigurationError, TransformerException
	{
		StreamSource xmlSource = new StreamSource(new StringReader(_node.getOuterXml()));
		File styleSheet = new File(xsltfilename);
		StreamSource styleSource = new StreamSource(styleSheet);
		Transformer t = TransformerFactory.newInstance().newTransformer(styleSource);
		StringWriter w = new StringWriter();
		StreamResult result = new StreamResult(w);
		try
		{
			t.transform(xmlSource, result);
			w.close();
		}
		catch (TransformerException e)
		{
		}
		catch (IOException e)
		{
		}
		return w.toString().substring(38);
	}
}

Leave a Reply

pagepeel by webpicasso.de