在android中的xml文件中添加新行字符,并在解析后保存它

时间:2015-12-01 07:55:01

标签: android xml

我有一个要解析的XML文件

<?xml version="1.0" encoding="UTF-8"?>
<Response>
<WiFi>
<SSID>testwifi</SSID>
<Key>testkey</Key>
</WiFi>
<Contact>
BEGIN:VCARD
VERSION:2.1
N:;AL entertainment;;;
FN:AL entertainment
TEL;CELL;PREF:543-212
END:VCARD
BEGIN:VCARD
VERSION:2.1
N:Gump;Forrest;;;
FN:Forrest Gump
TEL;CELL;PREF:543-404
EMAIL;PREF:satvinder94@gmail.com
END:VCARD
</Contact>
</Response>

我使用下面的代码解析它。

public boolean getXmlFromUrl() {

    boolean status = false;

    StringBuffer output = new StringBuffer("");

    try {

        InputStream stream = null;

        URL url = new URL("uploaded url to test server URL");

        URLConnection connection = url.openConnection();

        HttpURLConnection httpConnection = (HttpURLConnection)connection;

        httpConnection.setRequestMethod("GET");

        httpConnection.connect();

        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            stream = httpConnection.getInputStream()
            BufferedReader buffer = new BufferedReader(new InputStreamReader(stream));

            String s = "";

            while ((s = buffer.readLine()) != null

                output.append(s);

            status = true;
        }

        mScanXMLStr = output.toString();
        Log.d(TAG,"string :: "+mScanXMLStr);
    } catch (Exception ex) {

        ex.printStackTrace();
    }
    return status;
}

何我可以在联系人标签中保留新行,即从BEGIN:VCARD到END:VCARD?

2 个答案:

答案 0 :(得分:1)

首先,您应该将output.append(s)替换为output.append(s + \n),它将使用新的行符号从流中读取。是的,你不解析,你只读。如果你想解析,我会创建两个类:

public class XmlResponseParser{

    public static Response parse(String s){
        Response response = new Response();

        //as <SSID> and <Key> are inner parameters of <WiFi>, they should be          
        //looked for inside <WiFi> tag
        String wifiString = findTagValue(s, "WiFi");
        response.wifi.ssid = findTagValue(wifiString, "SSID");
        response.wifi.key = findTagValue(wifiString, "Key");
        response.contact = findTagValue(s, "Contact");

        return response;
    }
    //finds and returns value of tag in substring
    private static String findTagValue(String s, String tag){

        int startTagValueIndex = s.indexOf("<" + tag + ">") + tag.length() + 2;
        int endTagValueIndex = s.indexOf("</" + tag + ">");

        return s.substring(startTagValueIndex, endTagValueIndex);
    }

}

public class Response{
    WiFi wifi;
    String contact;

    public Response(){
        wifi = new WiFi();
    }


    public class WiFi{
        String ssid;
        String key;
    }
}

然后你可以在代码中调用XmlResponseParser.parse(mScanXMLStr),它将返回你和Response类的实例。

修改

另外,请查看SimpleXml library来解析XML

答案 1 :(得分:0)

尝试使用&amp; #xA而不是新行字符

这里有一个类似的答案:Preserve newlines when parsing xml