我正在研究需要xsl转换的android(2.2)项目。以下代码可在常规的非Android Java项目中完美运行
public static String transform() throws TransformerException {
Source xmlInput = new StreamSource(new File("samplexml.xml"));
Source xslInput = new StreamSource(new File("samplexslt.xslt"));
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(xslInput);
OutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
transformer.transform(xmlInput, result);
return baos.toString();
}
我需要在android上使用类似功能。为此,我在resources / raw下创建了2个文件:
samplexml.xml
样本xslt.xslt
(这些文件的内容来自here。
我尝试了下面的代码,但它不起作用(请注意StreamSource构造函数arg):
public static String transform() throws TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
Source xmlInput = new StreamSource(this.getResources().openRawResource(R.raw.samplexml));
Source xslInput = new StreamSource(this.getResources().openRawResource(R.raw.samplexslt));
Transformer transformer = factory.newTransformer(xslInput);//NullPointerException here
OutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
transformer.transform(xmlInput, result);
}
我看到了规格并认为我需要设置一个systemId。但是我无法使上面的代码正常工作。
那么,在android项目中,如何处理xslt转换?请提供您的想法。
最佳答案
我们知道we Cannot use
this
in a static context
,而您是在静态方法transform()
中执行此操作的。您可以像这样_
public class YourLoadXSLClass extends Activity {
static Resources res;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
res = getResources();
String strHTML = transform();
// Other code.....
}
/*
* Your method that Transform CSLT.
*/
public static String transform() throws TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
// Now your raw files are accessible here.
Source xmlInput = new StreamSource(
LoadXSLTinWebview.res.openRawResource(R.raw.samplexml));
Source xslInput = new StreamSource(
LoadXSLTinWebview.res.openRawResource(R.raw.samplexslt));
Transformer transformer = factory.newTransformer(xslInput);
OutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
transformer.transform(xmlInput, result);
return baos.toString();
}
}
Here是完成需要的完整类代码。希望这对您和所有人有帮助!