【问题标题】:XML parsing : encoding utf-8 & UTF-8XML 解析:编码 utf-8 & UTF-8
【发布时间】:2012-11-07 08:35:39
【问题描述】:

我试图解析来自这个LINK的值,它的xml编码是这样的

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

当我尝试 get response 在 logcat 中抛出消息时,如图所示

11-19 17:25:13.350: W/System.err(3360): This is not valid URL
11-19 17:25:13.350: W/System.err(3360): java.lang.NullPointerException

当我尝试使用其他一些 LINK 时,其编码是这样的

<?xml version="1.0" encoding="UTF-8"?> 工作正常,我可以解析值。

xml 解析失败,因为编码不是 UTF-8,是 utf-8 吗??

我应该如何处理这个问题。我做过谷歌,对 XML 解析很陌生。这是我尝试创建的第一个解析。请告诉我路。

已更新代码:

public String getXmlFromUrl(String url) {

    String xml = null;

    try {            
        // defaultHttpClient
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);           
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity(); 
        xml = EntityUtils.toString(httpEntity);
        System.out.println("response -- " + xml);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

【问题讨论】:

  • URL 本身似乎失败了不是吗?在读取 xml 之前
  • 但它可以在浏览器中工作..当然...我会更新我的代码..给我一秒钟
  • @DonRoby 更新了代码..
  • 两个网址都显示编码 -> UTF-8
  • @Atrix1987 in first url UTF is in SMALLER CASE & in other caps

标签: android xml-parsing xmlhttprequest domparser


【解决方案1】:

看起来问题在于您的响应中的 XML 编码。

URL url = new URL("http://myurl.com");
InputSource is = new InputSource(url.openStream());
is.setEncoding("ISO-8859-1"); // Also Try UTF-8 or UTF-16
BufferedReader br = new BufferedReader(new InputStreamReader(is.getByteStream()));
String line,str;
while((line=br.readLine())!=null)
{
      str = str + line;
}
Log.i(TAG,str);

【讨论】:

    【解决方案2】:

    检查响应的 content type 标头的 charset。它可以是 ISO-8859-1 或 UTF-8。相应地编码。

    编辑: 对于您提供的链接,我没有为响应设置任何编码。 既然您提到您是 XML 解析的新手,我将发布我的解析器实现。

    我的解析器:

    public final class SampleParser{
    
    
        final static String ROOT_NODE = "Menus";
        final static String ELEMENT_SITEMENU = "SiteMenu";
        final static String ELEMENT_ID = "menuID";
        final static String ELEMENT_TITLE = "menuTitle";
        final static String ELEMENT_CUSTOM = "menuIsCustom";
        final static String ELEMENT_PAGE_URL = "menuCustomPageURL";
        final static String ELEMENT_IOS_ID = "iosMenuID";
    
        private static final String TAG="SampleParser";
    
        /**
         * Intentionally commented
         */
        private SampleParser() {}
    
        /**
         * @param response The XML string which represents the complete news data
         * @return news The complete data
         */
        public static Menus parse(String response) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp;
            try {
                sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                SampleDataHandler dataHandler = new SampleDataHandler();
                xr.setContentHandler(dataHandler);
                InputSource source = new InputSource(new StringReader(response)); 
                xr.parse(source);
                Menus result = dataHandler.getData();
                return result;
            } catch (ParserConfigurationException e) {
                Log.e(TAG, "parse", e);
            } catch (SAXException e) {
                Log.e(TAG, "parse", e);
            } catch (IOException e) {
                Log.e(TAG, "parse", e);
            } 
            return null;
        }
    
        static class SampleDataHandler extends DefaultHandler {
            /**
             * 
             */
            private static final String TAG="SampleDataHandler";
            /**
             * 
             */
            private Menus data;
            /**
             * 
             */
            private SiteMenu tempElement;
            /**
             * 
             */
            private boolean readingIosId;
            /**
             * 
             */
            private boolean readingTitle;
            /**
             * 
             */
            private boolean readingID;
            /**
             * 
             */
            private boolean readingCustom;
            /**
             * 
             */
            private boolean readingCustomURL;
    
    
            /**
             * 
             */
            public Menus getData(){
                return data;
            }
    
            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.helpers.DefaultHandler#endDocument()
             */
            @Override
            public void endDocument() throws SAXException {
                Log.d(TAG, "endDocument Finished parsing response");
            }
    
            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String,
             * java.lang.String, java.lang.String)
             */
            @Override
            public void endElement(String uri, String localName, String qName)
                    throws SAXException {
                if(qName.equalsIgnoreCase(ELEMENT_SITEMENU)){
                    data.addMathematician(tempElement);
                }else if(qName.equalsIgnoreCase(ELEMENT_ID)){
                    readingID = false;
                }else if(qName.equalsIgnoreCase(ELEMENT_TITLE)){
                    readingTitle = false;
                }else if(qName.equalsIgnoreCase(ELEMENT_IOS_ID)){
                    readingIosId = false;
                }else if(qName.equalsIgnoreCase(ELEMENT_CUSTOM)){
                    readingCustom = false;
                }else if(qName.equalsIgnoreCase(ELEMENT_PAGE_URL)){
                    readingCustomURL = false;
                }
            }
    
            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.helpers.DefaultHandler#startDocument()
             */
            @Override
            public void startDocument() throws SAXException {
                data = new Menus();
                Log.d(TAG, "startDocument Started parsing response");
            }
    
            /*
             * (non-Javadoc)
             * 
             * @see
             * org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
             * java.lang.String, java.lang.String, org.xml.sax.Attributes)
             */
            @Override
            public void startElement(String uri, String localName, String qName,
                    Attributes attributes) throws SAXException {
                if(qName.equalsIgnoreCase(ROOT_NODE)){
                    //data.setData(new ArrayList<NewsElement>());
                }else if(qName.equalsIgnoreCase(ELEMENT_SITEMENU)){
                    tempElement = new SiteMenu();
                }else if(qName.equalsIgnoreCase(ELEMENT_IOS_ID)){
                    readingIosId = true;                
                }else if(qName.equalsIgnoreCase(ELEMENT_ID)){
                    readingID = true;
                }else if(qName.equalsIgnoreCase(ELEMENT_TITLE)){
                    readingTitle = true;
                }else if(qName.equalsIgnoreCase(ELEMENT_CUSTOM)){
                    readingCustom = true;
                }else if(qName.equalsIgnoreCase(ELEMENT_PAGE_URL)){
                    readingCustomURL = true;
                }
            }
    
            /*
             * (non-Javadoc)
             * 
             * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
             */
            @Override
            public void characters(char[] ch, int start, int length)
                    throws SAXException {
                String chars = new String(ch, start, length);    
                chars = chars.trim(); 
                if(readingID){
                    try{
                        tempElement.setId(Integer.parseInt(chars));
                    }catch(Exception e){
                        Log.e(TAG, "characters[Parsing ID]", e);
                        tempElement.setId(-1);
                    }
                }
                else if(readingIosId){
                    try{
                        tempElement.setiOSID(Integer.parseInt(chars));
                    }catch(Exception e){
                        Log.e(TAG, "characters[Parsing iOSID]", e);
                        tempElement.setiOSID(-1);
                    }
                }else if(readingTitle){
                    tempElement.setTitle(chars);
                }else if(readingCustom){
                    try{
                        tempElement.setCustom(Boolean.parseBoolean(chars));
                    }catch(Exception e){
                        Log.e(TAG, "characters[Parsing custom]", e);
                        tempElement.setCustom(false);
                    }
                }else if(readingCustomURL){
                    tempElement.setCustomUrl(chars);
                }
            }
        }
    }
    

    我用于网络调用的 utils 方法。 [和你一样]

        /**
         * @param url
         * @return
         */
        private static HttpEntity getResponseEntity(String url) {
    
            DefaultHttpClient httpClient = getHttpClient();
    
            HttpGet getMethod = new HttpGet(url);
            long startTime= 0;
    
            try {
                HttpResponse httpResponse = httpClient.execute(getMethod);
    
                HttpEntity responseEntity = httpResponse.getEntity();
                return responseEntity;
    
            } catch (IOException ioe) {
                Log.e(TAG, "getResponseEntity", ioe);
            } catch (Exception e) {
                Log.e(TAG, "getResponseEntity", e);
            } 
            return null;
        }
    
        /**
         * @param url
         * @return
         */
        public static String getRespAsString(String url) {
    
            if (!ApplicationInfo.networkStatus) {
                // No Internet Connection
                return null;
            }
    
            try {
                HttpEntity responseEntity = getResponseEntity(url);
                if (responseEntity != null)
                    return EntityUtils.toString(responseEntity);
                else
                    return null;
            } catch (Exception e) {
                Log.e(TAG, "getRespAsString", e);
            }
    
            return null;
        }
    

    只需获取响应并调用解析器,例如。 SampleParser.parse(response);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-16
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 2010-10-26
      • 1970-01-01
      相关资源
      最近更新 更多