2010-11-23 3 views

ответ

1

Возможно, вы также можете использовать собственный парсер SAX для Android. Я пробовал использовать его, и он отлично работает. Это также основано на образце кода с сайта IBM.

public class ParseXML { 

private URL feedUrl; 

public ParseXML(String urlSource){ 
    try { 
     this.feedUrl = new URL(urlSource); 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } 
} 


protected InputStream getInputStream() { 
    try { 
     return feedUrl.openConnection().getInputStream(); 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 


public YourDataContainer parse(){ 
    YourDataContainer container = new YourDataContainer(); 

    RootElement root = new RootElement("root"); 

    Element firstChild = root.getChild("element1"); 
    firstChild.getChild("entry1").setEndTextElementListener(new EndTextElementListener() { 

     public void end(String body) { 
      container.setFirstEntry(body); 
     } 
    }); 
    firstChild.getChild("entry2").setEndTextElementListener(new EndTextElementListener() { 

     public void end(String body) { 
      container.setSecondEntry(body); 
     } 
    }); 


    try { 
     Xml.parse(this.getInputStream(), Xml.Encoding.ISO_8859_1, root.getContentHandler()); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (SAXException e) { 
     e.printStackTrace(); 
    } 
    return container; 
} 

Где у вашего Контейнера есть поля для значений, которые вы хотите сохранить, а также получатели и сеттеры.

Это будет разбирать что-то вроде этого:

<root> 
    <element1> 
     <entry1>this is</entry1> 
     <entry2>a test</entry2> 
    </element1> 
</root> 

В конце пробега, YourContainer будет иметь firstEntry = «это» и secondEntry = «тест».

1

Я свяжу вас с my answer here. Это должно помочь вам начать работу. Для основ, просто Google Java SAX Parsing.

Смежные вопросы