2011-06-02 63 views

回答

4

将您的xml和xslt文件放在原始文件夹中。 生成的html文件将被存储在SD卡中。 使用下面的代码。

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

感谢 迪帕克

+0

@Deepak:感谢您的答复。这给我错误“应用程序意外停止,请再试一次”。我使用了给定链接中使用的相同的xsl和xml文件。谢谢 – har 2011-06-02 14:22:30

+1

从url下载示例xml和xslt文件。但给出单独的名称并将其粘贴到原始文件夹中http://codingwithpassion.blogspot.com/2010/12/transform-xml-into-html-using-xslt.html – 2011-06-02 14:28:35

+0

@Deepak:我使用了准确的代码,原始文件夹中的xml和xslt文件(我手动创建了原始文件夹) 现在我没有得到任何错误,但没有输出。 我能做什么? – har 2011-06-02 14:44:35

0

不要忘了补充:

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

AndroidManifest.xml因为这小白终于找到了:)

+4

这应该作为对问题的评论。虽然有用,但它不回答这个问题。 – Amy 2011-11-10 03:31:36