2012-05-10 47 views
0

嗨即時嘗試從FTP服務器讀取XML文件並解析它。Android的FTP輸入流到XML

但我不能夠使用我的字符串作爲輸入源。我可以看到無法讀取LogCat中的文件,並且可以在瀏覽器中打開XMl文件。但我不確定如何使用字符串作爲輸入源。

CODE:

public void readXML(){ 

    try { 
     Log.e("FTP", "Starting ftp session"); 

     FTPClient ftp = new FTPClient(); 

     Log.e("FTP", "Connecting to FTP"); 
     ftp.connect("ftp.domain.com"); 

     Log.e("FTP", "Providing credentials to FTP"); 
     ftp.login("user", "pswd"); 
     if(ftp.login("user", "pswd")){ 
      Log.e("FTP", "Was able to connect to FTP"); 
     } 

     ftp.enterLocalPassiveMode(); 
     ftp.changeWorkingDirectory("/folder/XML"); 

     Log.e("FTP", "Getting stream"); 
     InputStream inStream = ftp.retrieveFileStream("file.xml"); 
     InputStreamReader isr = new InputStreamReader(inStream, "UTF8"); 
     BufferedReader reader = new BufferedReader(isr); 

     String Input = ""; 
     Log.e("FTP", "Reading filestream"); 

     do{ 
      Input = Input + reader.readLine() + "\n"; 
      Log.e("FTP", reader.readLine()); 

     }while(reader.readLine()!=null);    

     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 

     Log.e("FTP", "Parsing inputsource"); 
     Document doc = db.parse(new InputSource(new StringReader(Input))); 
     doc.getDocumentElement().normalize(); 

     Log.e("FTP", "Creating nodelist"); 
     NodeList nodeList = doc.getElementsByTagName("TAG"); 

林不確定的,如果StringReader是要走的正確途徑。

編輯:

由於拉傑什

這是我的解決方案:

public void readXML(){ 

    try { 
     Log.e("FTP", "Starting ftp session"); 

     FTPClient ftp = new FTPClient(); 

     Log.e("FTP", "Connecting to FTP"); 
     ftp.connect("ftp.domain.com"); 

     Log.e("FTP", "Providing credentials to FTP"); 
     ftp.login("user", "pswd"); 
     if(ftp.login("user", "pswd")){ 
      Log.e("FTP", "Was able to connect to FTP"); 
     } 

     ftp.enterLocalPassiveMode(); 
     ftp.changeWorkingDirectory("/folder/XML"); 

     Log.e("FTP", "Getting stream"); 
     InputStream inStream = ftp.retrieveFileStream("file.xml");   

     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 

     Log.e("FTP", "Parsing inputsource"); 
     Document doc = db.parse(new InputSource(inStream)); 
     doc.getDocumentElement().normalize(); 

     Log.e("FTP", "Creating nodelist"); 
     NodeList nodeList = doc.getElementsByTagName("TAG"); 
+0

您是否收到任何錯誤?如果是這樣,請發佈。從'StringReader'創建'InputSource'完全有效。 – Rajesh

回答

0

一些建議/意見:

  1. 您可以從InputStream直接創建InputSource無具有中間String
  2. 相反通過附加String的多重次創建String的,這將是有效地使用StringBuffer
  3. 使用以下代碼將導致的交替行(以及可能無效的XML跳過 - 這可能是問題你的情況)

    do{ 
        Input = Input + reader.readLine() + "\n"; 
        Log.e("FTP", reader.readLine()); 
    
    }while(reader.readLine()!=null); 
    
+0

謝謝! Document doc = db.parse(new InputSource(inStream)); – Patrick