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直接从中创建InputStream而无需中间String
  2. 与其通过多次String附加s来创建 a ,不如使用它是有效的StringStringBuffer
  3. 使用以下代码将导致跳过备用行(并且可能是无效的 XML - 这可能是您问题)

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