Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try something along the lines of this:</p> <pre><code>public class XmlParser extends DefaultHandler{ private static final int STATE_FEED = 0; private static final int STATE_ID = 1; private static int sDepth = 0; private static int sCurrentState = 0; private String mTheString; public XmlParser(){} @Override public void startDocument() throws SAXException{} @Override public void endDocument() throws SAXException{} @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException{ mTheString = ""; sDepth++; if (qName.equals("feed")){ sCurrentState = STATE_FEED; return; } if (qName.equals("id")){ sCurrentState = STATE_ID; return; } sCurrentState = 0; } @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException{ sDepth--; switch (sCurrentState){ case STATE_FEED: //Do something with the feed sCurrentState = 0; mTheString = ""; break; case STATE_ID: // Save the ID or do whatever sCurrentState = 0; mTheString = ""; break; default: //Do nothing mTheString = ""; return; } mTheString = ""; } @Override public void characters(char ch[], int start, int length){ mTheString = mTheString + new String(ch, start, length); } </code></pre> <p>}</p> <p>You can access the custom SAXParser with something like this:</p> <pre><code>InputStream stream = //whatever your stream is (the document) XmlParser handler = new XmlParser(); // your custom parser XMLReader xmlreader = XMLReaderFactory.createXMLReader(); xmlreader.setContentHandler(handler); xmlreader.parse(new InputSource(stream)); // Then you can create a method in the handler, like getResults to return the list of elements or something here. </code></pre> <p>So you pass your custom parser into the Xml Reader, and get the results from the source. During the Xml Parsing, the handler starts at "start document" then iterates through the elements in the xml (calling startElement at the start, endElement at the beginning). The characters method is called in between these two - picking up the characters (which you can then do whatever you want with in the endElement). The parser is finished when endDocument is called, so you can set things up and tear them down at the start and end of elements or the whole document if you wish.</p> <p>Hope this helps, and is close to what you are looking to do.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload