На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
Модераторы: Hsilgos
Страницы: (2) 1 [2]  все  ( Перейти к последнему сообщению )  
> Парсинг xml
    В общем-то:
    ExpandedWrap disabled
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(xml));
      doc = db.parse(is);

    должно работать. без каких либо указаний кодировок, потому что на входе у вас String. А он бывает только в одной кодировке.
    1. Проверьте что у вас в строке на входе в метод XMLfromString, если она битая, то дальше ничего уже не исправить.
    2. У вас Response от сервера сначала перегоняеться в строку, а потом из строки в xml документ. Это лишние действия:
    ExpandedWrap disabled
              final HttpResponse response = mHttpClient.execute(request);
          final InputStream in = response.getEntity().getContent();
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          factory.setNamespaceAware(true); // never forget this!
          DocumentBuilder builder = factory.newDocumentBuilder();
          Document doc = builder.parse(in);

    этот фрагмент гарантированно работает с UTf-8.
      Британский учёный
      ExpandedWrap disabled
        public class XMLParser {
         
            public final static Document XMLfromString(String xml){
                
                Document doc = null;
                
                //DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                //DocumentBuilder builder = dbf.newDocumentBuilder();
                try {
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = dbf.newDocumentBuilder();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    //StringReader sr = new StringReader(xml);
                    //InputSource is = new InputSource(sr);
                    //is.setCharacterStream(new StringReader(xml));
                    //is.setEncoding("utf-8");
                    ByteArrayInputStream encXML = new ByteArrayInputStream(xml.getBytes("UTF8"));
                    doc = builder.parse(encXML);
                    
                } catch (ParserConfigurationException e) {
                    System.out.println("XML parse error: " + e.getMessage());
                    return null;
                } catch (SAXException e) {
                    System.out.println("Wrong XML file structure: " + e.getMessage());
                    return null;
                } catch (IOException e) {
                    System.out.println("I/O exeption: " + e.getMessage());
                    return null;
                }
                      
                return doc;
                
            }


      методом тыка испробовал много вариантов...всё равно кодировку не меняет(

      Добавлено
      mrco знаний не хватает - проверить что в строке на входе(((

      Добавлено
      mrco Я слегка не понимаю про Response... У меня всё тоже самое, кроме одной строчки, только раскидано между функциями...

      ExpandedWrap disabled
        public class XMLParser {
         
            public final static Document XMLfromString(String xml){
                
                Document doc = null;
                
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true); // never forget this!
                try {
                    
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    
                    InputSource is = new InputSource();
                    is.setCharacterStream(new StringReader(xml));
                    doc = db.parse(is);
                    
                } catch (ParserConfigurationException e) {
                    System.out.println("XML parse error: " + e.getMessage());
                    return null;
                } catch (SAXException e) {
                    System.out.println("Wrong XML file structure: " + e.getMessage());
                    return null;
                } catch (IOException e) {
                    System.out.println("I/O exeption: " + e.getMessage());
                    return null;
                }
                      
                return doc;
                
            }
            
            /** Returns element value
              * @param elem element (it is XML tag)
              * @return Element value otherwise empty String
              */
             public final static String getElementValue( Node elem ) {
                 Node kid;
                 if( elem != null){
                     if (elem.hasChildNodes()){
                         for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                             if( kid.getNodeType() == Node.TEXT_NODE  ){
                                 return kid.getNodeValue();
                             }
                         }
                     }
                 }
                 return "";
             }
                
             public static String getXML(){  
                    String line = null;
         
                    try {
                        
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost("http://alfoot.net/newfile.xml");
         
                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        InputStream in = httpResponse.getEntity().getContent();//
                        HttpEntity httpEntity = httpResponse.getEntity();
                        line = EntityUtils.toString(httpEntity);
                        
                    } catch (UnsupportedEncodingException e) {
                        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                    } catch (MalformedURLException e) {
                        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                    } catch (IOException e) {
                        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                    }
         
                    return line;
         
            }
            // final HttpResponse response = mHttpClient.execute(request);
             //   final InputStream in = response.getEntity().getContent();
            
            public static int numResults(Document doc){    
                Node results = doc.getDocumentElement();
                int res = -1;
                
                try{
                    res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
                }catch(Exception e ){
                    res = -1;
                }
                
                return res;
            }
         
            public static String getValue(Element item, String str) {      
                NodeList n = item.getElementsByTagName(str);        
                return XMLParser.getElementValue(n.item(0));
            }
        }
        Самое обидное...то, что уже столько получилось копипастом...и на одной фишке легло(((

        Добавлено
        Это переменная doc
        03-28 13:58:07.523: I/System.out(305): !: org.apache.harmony.xml.dom.DocumentImpl@44f69f88
        Переменная line в месте где должны быть наши буковки русские...уже хранит абракадабру -
        03-28 13:59:44.493: I/System.out(333): <name>Команда А - Команда Б</name>

        mrco, вы имели в виду этот вход? Или есть ещё где?
          Цитата muskos @
          Переменная line в месте где должны быть наши буковки русские...уже хранит абракадабру -

          Тоесть ПЕРЕД парсингом уже фигня в строке? Тогда парсер не причёмю
            На всякий случай покажу, где переменная line лежит...и в какой момент она что делает...

            ExpandedWrap disabled
              public static String getXML(){  
                          String line = null;
               
                          try {
                              
                              DefaultHttpClient httpClient = new DefaultHttpClient();
                              HttpPost httpPost = new HttpPost("http://alfoot.net/newfile.xml");
               
                              HttpResponse httpResponse = httpClient.execute(httpPost);
                              HttpEntity httpEntity = httpResponse.getEntity();
                              line = EntityUtils.toString(httpEntity);
                              
                          } catch (UnsupportedEncodingException e) {
                              line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                          } catch (MalformedURLException e) {
                              line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                          } catch (IOException e) {
                              line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                          }
               
                          return line;
               
                  }


            Хорошо, тогда ЧТО ЖЕ ЭТО МОЖЕТ БЫТЬ((( У МЕНЯ УЖЕ ГОЛОВА КРУГОМ)))) :crazy:
              С сервера xml приходит в какой кодировке?
              Если utf-8 то попробуйте line = EntityUtils.toString(httpEntity, "UTF-8");
                mrco Я ПРОСТО В ШОКЕ!!!!!!!!!! СПАСИБО БОЛЬШОЕ!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
                0 пользователей:


                Рейтинг@Mail.ru
                [ Script execution time: 0,0387 ]   [ 15 queries used ]   [ Generated: 28.03.24, 12:27 GMT ]