Android: Convert xml using xslt

匿名 (未验证) 提交于 2019-12-03 02:05:01

问题:

I want to transform some xml using an xsl-file and output the result somehow (I'm using Android Api Level 8).

My current activity looks like this, but the transformer stays null. LogCat throws an System.err with org.apache.harmony.xml.ExpatParser$ParseException, saying the xml is not well-formed, but I made sure it is.

I found a hint in LogCat that says SystemId Unknown just before the above error message.

What am I doing wrong?

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();         }     } } 

This is the xml-file to be transformed (source.xml)

PaulMcCartneySingerMale

And this is the corresponding xsl (products.xsl)

回答1:

There really isn't a lot of room for error in such a small piece of code. My guess is that the XML or XSL is to blame after all. There's probably a tiny typo in it. Can you attach the XML/XSLT as well?



回答2:

I just found out what the problem is: I put the XML/XSLT files in res/xml not in res/raw with the result of mangled XML format.

Much ado about nothing :(



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!