Convert XML file using XSLT in Android

2019-06-05 15:40发布

问题:

I am new to Android.

I want to convert a XML file to HTML format using XSLT to display it in android.

Can you please tell me some tutorials or examples to follow?

I also tried the codes in the Android: Convert xml using xslt But it didn't work. I am not sure what is "StringOutputStream" there.

Thanks in advance.

回答1:

Put both your xml and xslt file in raw folder. The generated html file will be stored in sdcard. Use the following code.

import java.io.File;

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;
import android.os.Environment;

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.raw.weather));
            Source xsltSource = new StreamSource(this.getResources().openRawResource(R.raw.weatherxsl));

            TransformerFactory transFact = TransformerFactory.newInstance();
            Transformer trans = transFact.newTransformer(xsltSource);
//          FileOutputStream fo = new FileOutputStream(f);
//          fo.write(resizeBitMapImageToByteArray(photoAlbumBean));
//          fo.close();
            File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mydata.html");

//            OutputStream output = new StringOutputStream();
            StreamResult result = new StreamResult(f);
            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();
        }
    }
}

Thanks Deepak



回答2:

Don't forget to add:

< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

to the AndroidManifest.xml as this noob eventually found out :)



标签: android xml xslt