Search code examples
androidxml-parsingsax

Android SAXParse Get Value Between Tags


I have an XML file I am reading in via SAXParser, but I am having trouble reading it in correctly. The XML is structured like this:

<game>
  <players>
    <player>
      <name>Player 1</name>
      <score>100</score>
    </player>
  </players>
</game>

How can I get the Android SAXParser to read the values between tags? This is the code that I have, but it is looking for an attribute to the tag, not the text between.

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

    if(localName.equals("name")) {
        names.add(attributes.getValue("name"));
    }
    else if(localName.equals("score")) {    
        scores.add(Integer.parseInt(attributes.getValue("score")));
    }

}

Solution

  • Drawing from the example @

    http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

    More info about sax @

    http://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html

    Apart from sax you should have a look at xmllpullparser which is recommended.

    Quoting from the docs.

    We recommend XmlPullParser, which is an efficient and maintainable way to parse XML on Android.

    Check the link @

    http://developer.android.com/training/basics/network-ops/xml.html

    public void readxml(){ 
            try {
    
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();
    
            DefaultHandler handler = new DefaultHandler() {
    
            boolean bname = false;
            boolean bscore = false;
    
    
            public void startElement(String uri, String localName,String qName, 
                        Attributes attributes) throws SAXException {
    
                if (qName.equalsIgnoreCase("name")) {
                    bname = true;
                }
    
                if (qName.equalsIgnoreCase("score")) {
                    bscore = true;
                }
            }
    
            public void endElement(String uri, String localName,
                String qName) throws SAXException {
    
            }
    
            public void characters(char ch[], int start, int length) throws SAXException {
    
                if (bname) {
                    Toast.makeText(getApplicationContext(), new String(ch, start, length), 10000).show();
                    bname = false;
                }
    
                if (bscore) {
                    Toast.makeText(getApplicationContext(), new String(ch, start, length), 10000).show();
                    bscore = false;
                }
            }
          };
    
               saxParser.parse("myxmltoparse", handler);
    
             } catch (Exception e) {
               e.printStackTrace();
             }
    
           }
    }