我怎样才能摆脱这个额外的角色?在xml读取

时间:2012-03-13 19:41:35

标签: xml

我的xml文件的开头出现了一个额外的字符,这反过来导致我的解析方法出错。我正在使用InputStreamReader从URL读取文件。

?<?xml version="1.0" encoding="utf-8"?>

我的代码,如果有兴趣

public class Client {

private static final String TAG = "Client";
public Client(){

}

InputStream executePost(String targetURL, String urlParameters){

    URL url;
    HttpURLConnection connection = null;        
    try{
        //Create connection

        url = new URL(targetURL);
        //Log.i(TAG,"Connecting to : "+targetURL);
        connection = (HttpURLConnection)url.openConnection();

        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", 
                   "text/xml; charset=utf-8");
        connection.setRequestProperty("Content-Language", "en-US"); 
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);



        //get response
        InputStream is = connection.getInputStream();
        InputStreamReader reader = new InputStreamReader(is,"UTF-8");

        BufferedReader br = new BufferedReader(reader);
        String line ="";

        while((line = br.readLine()) != null){
            System.out.println(line);

        }


        return is;


    }catch(Exception e){
        //Log.i(TAG,"Unable to create connection");
        e.printStackTrace();
        return null;
    }finally {

          if(connection != null) {
            //Log.i(TAG,"Disconnecting");
            connection.disconnect(); 
          }
    }


}

}

1 个答案:

答案 0 :(得分:1)

这是一个所谓的BOM,(字节顺序标记),您应该使用xml解析器实例来读取可以处理它的xml文件。