0

こんにちは、FTP サーバーから XML ファイルを読み取って解析しようとしています。

しかし、文字列を入力ソースとして使用できません。LogCat でファイルを読み取ることができ、ブラウザで XML ファイルを開くことができます。しかし、文字列を入力ソースとして使用する方法がわかりません。

コード:

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");
4

1 に答える 1

0

いくつかの提案/観察:

  1. 中間体なしでInputSourceから直接作成できますInputStreamString
  2. Strings を複数回追加して a を作成する代わりに、String使用すると効率的ですStringBuffer
  3. 次のコードを使用すると、代替行がスキップされます (および無効な XML の可能性があります -あなたの場合問題になる可能性があります)。

    do{
        Input = Input + reader.readLine() + "\n";
        Log.e("FTP", reader.readLine());
    
    }while(reader.readLine()!=null);  
    
于 2012-05-10T12:50:55.367 に答える