poniedziałek, 14 listopada 2016

Java - stop reading possibly huge xml once given element found

  Path versionFile = installationPath.resolve("large.xml");

  SAXParserFactory factory = SAXParserFactory.newInstance();
  SAXParser parser = factory.newSAXParser();

  InputStream is = openStream(versionFile);

  class BreakException extends SAXException {
   private String value = null;
   private static final long serialVersionUID = 1L;
  }

  try {
   parser.parse(is, new DefaultHandler() {
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
     if ("InstallType".equals(qName)) {
      String value = attributes.getValue("currentVersion");
      // really dirty way to break sax parsing on demand and return value out of anonymous handle by the way ;)
      BreakException breakException = new BreakException();
      breakException.value = value;
      throw breakException;
     }
    }
   });
  } catch (BreakException be) {
   return be.value;
  }

Brak komentarzy:

Prześlij komentarz