Android / JSoup - 从标签中获取价值

时间:2017-10-10 10:45:20

标签: android jsoup

我从外部设备接收数据并将其作为文本文件保存在移动设备上。我的问题是 - 我需要从该文本文件中获取值userID。值保留在标记中。例如

<user>1234</user>

我正在尝试使用JSoup来实现这一目标,但我有一些复杂性。

这是我的代码:

public CommunicationThread(Socket clientSocket) {
            this.clientSocket = clientSocket;
            try {
                InputStream in = this.clientSocket.getInputStream();
                Date date = new Date();
                File root = new File("/sdcard/mente/" + user.getID() );
                if(!root.exists())
                root.mkdirs();
                String fileName = connectedDeviceSerialNumber + "_" + date + ".txt".replace(" ","_");
                file = new File(root,fileName);
                OutputStream out = new FileOutputStream(file);
                int count;
                StringBuilder sb = new StringBuilder();

                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                    for (byte b : bytes) {
                        sb.append(String.format("%02X ", b));
                    }
                    Log.e(TAG, "CommunicationThread: " + sb.toString() );
                    if (sb.toString().contains("3C 65 6E 64 5F 72 61 77 3E 74 72 75 65 3C 2F 65 6E 64 5F 72 61 77 3E") && syncProgressDialog != null) {
                        syncProgressDialog.dismiss();
                    }

                }
                Document doc = Jsoup.parse(sb.toString());
                Elements el = doc.select("user");
                String userId = el.attr("user");
                Log.e(TAG, "STR: " + userId );


                this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream(), Charset.forName("ISO-8859-2")));
                Log.e(TAG, "synchData1: ");

            } catch (IOException e) {
                Log.e(TAG, "error: " + e.getMessage());
            }
        }

提前感谢您的帮助:)

1 个答案:

答案 0 :(得分:2)

我的猜测是你没有正确地收到文字

<强>代替

Document doc = Jsoup.parse(sb.toString());
Elements el = doc.select("user");
String userId = el.attr("user");

你应该

String userId = "";

Document doc = Jsoup.parse(sb.toString());
Elements el = doc.select("user"); // el is an ArrayList... not a single element...
if(!el.isEmpty()) {
    Element singleElement = el.get(0);
    if (singleElement.hasText()) {
        userId = singleElement.text(); // Don't read attr... but text()
    } else {
        Log.e(TAG, "tag <user> has no text");
    }
} else {
    Log.e(TAG, "tag <user> not fould");
}

修改

我使用以下格式的文件进行了测试:

<user>1234</user>
<pass>1234</pass>

工作正常。你说不适合你,所以,sb.toString()可能不包含正确的文本(你可以记录确认...... Log.e(TAG, "sb: " + sb.toString());),或者它有不同的格式,我测试过.. ..所以,请分享你正在阅读的字符串示例。