Парсинг xml
    
  ![]()  | 
Наши проекты:
 Журнал · Discuz!ML · Wiki · DRKB · Помощь проекту  | 
|
| ПРАВИЛА | FAQ | Помощь | Поиск | Участники | Календарь | Избранное | RSS | 
| [216.73.216.5] | 
 
 | 
		
  | 
| Страницы: (2) 1 [2] все ( Перейти к последнему сообщению ) | 
    Парсинг xml
    
  | 
         
         
         
          
           Сообщ.
           #16
          
          , 
          
         
         
        
       | 
    |
| 
         | 
      
          В общем-то: 
        
      ![]() ![]() InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); doc = db.parse(is); должно работать. без каких либо указаний кодировок, потому что на входе у вас String. А он бывает только в одной кодировке. 1. Проверьте что у вас в строке на входе в метод XMLfromString, если она битая, то дальше ничего уже не исправить. 2. У вас Response от сервера сначала перегоняеться в строку, а потом из строки в xml документ. Это лишние действия: ![]() ![]()         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.  | 
    
| 
         
         
         
          
           Сообщ.
           #17
          
          , 
          
         
         
        
       | 
    |
| 
         | 
      
          Британский учёный 
        
      ![]() ![]() 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... У меня всё тоже самое, кроме одной строчки, только раскидано между функциями... ![]() ![]() 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));     } }  | 
    
| 
         
         
         
          
           Сообщ.
           #18
          
          , 
          
         
         
        
       | 
    |
| 
         | 
      
          Самое обидное...то, что уже столько получилось копипастом...и на одной фишке легло(((  
        
      Добавлено Это переменная 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, вы имели в виду этот вход? Или есть ещё где?  | 
    
| 
         
         
         
          
           Сообщ.
           #19
          
          , 
          
         
         
        
       | 
    |
| 
         | 
      
         Цитата muskos @  Переменная line в месте где должны быть наши буковки русские...уже хранит абракадабру -  Тоесть ПЕРЕД парсингом уже фигня в строке? Тогда парсер не причёмю  | 
    
| 
         
         
         
          
           Сообщ.
           #20
          
          , 
          
         
         
        
       | 
    |
| 
         | 
      
          На всякий случай покажу, где переменная line лежит...и в какой момент она что делает... 
        
      ![]() ![]() 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;     } Хорошо, тогда ЧТО ЖЕ ЭТО МОЖЕТ БЫТЬ((( У МЕНЯ УЖЕ ГОЛОВА КРУГОМ))))     | 
    
| 
         
         
         
          
           Сообщ.
           #21
          
          , 
          
         
         
        
       | 
    |
| 
         | 
      
          С сервера xml приходит в какой кодировке? 
        
      Если utf-8 то попробуйте line = EntityUtils.toString(httpEntity, "UTF-8");  | 
    
| 
         
         
         
          
           Сообщ.
           #22
          
          , 
          
         
         
        
       | 
    |
| 
         | 
      
          mrco Я ПРОСТО В ШОКЕ!!!!!!!!!! СПАСИБО БОЛЬШОЕ!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!   
        
       |