我想使用 xsl 文件转换一些 xml 并以某种方式输出结果(我使用的是 Android Api Level 8)。
我当前的 Activity 看起来像这样,但转换器保持为空。
LogCat 抛出一个 System.err
和 org.apache.harmony.xml.ExpatParser$ParseException
,说 xml 格式不正确,但我确定它是。
我在 LogCat 中发现一个提示,在上述错误消息之前显示 SystemId Unknown
。
我做错了什么?
import java.io.OutputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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;
import android.app.Activity;
import android.os.Bundle;
public class XsltTester extends Activity {
private static String TAG = XsltTester.class.getSimpleName();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Source xmlSource = new StreamSource(this.getResources().openRawResource(R.xml.source));
Source xsltSource = new StreamSource(this.getResources().openRawResource(R.xml.products));
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer(xsltSource);
OutputStream output = new StringOutputStream();
StreamResult result = new StreamResult(output);
trans.transform(xmlSource, result);
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是要转换的 xml 文件 (source.xml)
<?xml version="1.0"?>
<!-- <?xml-stylesheet href="beatle.xsl" type="text/xsl"?> -->
<person>
<name>
<firstname>Paul</firstname>
<lastname>McCartney</lastname>
</name>
<job>Singer</job>
<gender>Male</gender>
</person>
这是对应的xsl(products.xsl)
<xsl:template match="child::person">
<html>
<head>
<title>
<xsl:value-of select="descendant::firstname" />
<xsl:text> </xsl:text>
<xsl:value-of select="descendant::lastname" />
</title>
</head>
<body>
<xsl:value-of select="descendant::firstname" />
<xsl:text> </xsl:text>
<xsl:value-of select="descendant::lastname" />
</body>
</html>
</xsl:template>
</xsl:stylesheet>
最佳答案
这么小的一段代码确实没有太多出错的余地。我的猜测是 XML 或 XSL 才是罪魁祸首。里面可能有一个小错字。您也可以附上 XML/XSLT 吗?
关于java - Android:使用 xslt 转换 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4153560/