@Override public Object parseXml(String xmlString) { final ArrayList<ColourDAO> colours = new ArrayList<ColourDAO>(); RootElement rootElement = new RootElement(Tags.COLOURS); Element modelElement = rootElement.getChild(Tags.COLOUR); modelElement.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attributes) { colourDAO = new ColourDAO(attributes.getValue(Tags.ID), ""); } }); modelElement.setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { if (!TextUtils.isEmpty(body)) { colourDAO.name = body; colours.add(colourDAO); } } }); try { Xml.parse(xmlString, rootElement.getContentHandler()); } catch (SAXException e) { e.printStackTrace(); } return colours; }
public ArrayList<Bundle> parse() throws ParseException { final Bundle currentBundle = new Bundle(); RootElement root = new RootElement("bundles"); final ArrayList<Bundle> bundles = new ArrayList<Bundle>(); root.getChild("bundle") .setStartElementListener( new StartElementListener() { public void start(Attributes attributes) { String tags = attributes.getValue("", "tags"); String name = attributes.getValue("", "name"); if (tags != null) { currentBundle.setTagString(tags); } if (name != null) { currentBundle.setName(name); } bundles.add(currentBundle.copy()); } }); try { Xml.parse(is, Xml.Encoding.UTF_8, root.getContentHandler()); } catch (Exception e) { throw new ParseException(e.getMessage(), 0); } return bundles; }
public static void fillData2(final Story s) { URL storyURL; try { storyURL = new URL(mobileStoryUrlBase + s.url.substring(s.url.lastIndexOf('/'))); } catch (MalformedURLException e) { throw new RuntimeException("Malformed story url"); } RootElement html = new RootElement("http://www.w3.org/1999/xhtml", "html"); Element body = html.getChild("body"); body.setTextElementListener( new TextElementListener() { private ParseState state = ParseState.OTHER; /** * We don't know which element we are at in end(). So to know when the body div is ending, * keep track of how many elements have started and ended */ private int depth = 0; @Override public void start(Attributes attributes) { if (attributes.getValue("class").equals(PHOTO_CLASS)) state = ParseState.PHOTO; else if (state == ParseState.PHOTO) s.imgUrl = attributes.getValue("src"); else if (attributes.getValue("class").equals(BODY_CLASS)) { state = ParseState.BODY; s.text = ""; } else if (state == ParseState.BODY) depth++; } @Override public void end(String body) { if (state == ParseState.BODY) { if (depth == 0) state = ParseState.OTHER; else { s.text = s.text + body; depth--; } } } }); body.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attributes) { // Log.d("isd", "class2: " + attributes.getValue("class")); } }); try { Xml.parse( storyURL.openConnection().getInputStream(), Xml.Encoding.UTF_8, html.getContentHandler()); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Parses the. * * @param xml the xml * @return the list´ * @author RayBa * @throws SAXException * @date 07.04.2013 */ public List<Channel> parse(String xml) throws SAXException { RootElement channels = new RootElement("channels"); Element rootElement = channels.getChild("root"); Element groupElement = rootElement.getChild("group"); Element channelElement = groupElement.getChild("channel"); Element logoElement = channelElement.getChild("logo"); Element subChanElement = channelElement.getChild("subchannel"); channels.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attributes) { channelList = new ArrayList<Channel>(); } }); channelElement.setStartElementListener( new StartElementListener() { public void start(Attributes attributes) { currentChannel = new Channel(); currentChannel.setChannelID(Long.valueOf(attributes.getValue("ID"))); currentChannel.setPosition(Integer.valueOf(attributes.getValue("nr"))); currentChannel.setName(attributes.getValue("name")); currentChannel.setEpgID(Long.valueOf(attributes.getValue("EPGID"))); channelList.add(currentChannel); } }); logoElement.setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { currentChannel.setLogoUrl(body); } }); subChanElement.setStartElementListener( new StartElementListener() { public void start(Attributes attributes) { Channel c = new Channel(); c.setChannelID(Long.valueOf(attributes.getValue("ID"))); c.setName(attributes.getValue("name")); c.setPosition(currentChannel.getPosition()); c.setEpgID(currentChannel.getEpgID()); c.setLogoUrl(currentChannel.getLogoUrl()); c.setFlag(Channel.FLAG_ADDITIONAL_AUDIO); channelList.add(c); } }); Xml.parse(xml, channels.getContentHandler()); return channelList; }
public List<Message> parse() { final Message currentMessage = new Message(); RootElement root = new RootElement(RSS); final List<Message> messages = new ArrayList<Message>(); Element channel = root.getChild(CHANNEL); Element item = channel.getChild(ITEM); item.setEndElementListener( new EndElementListener() { public void end() { messages.add(currentMessage.copy()); } }); item.getChild(TITLE) .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentMessage.setTitle(body); } }); item.getChild(LINK) .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentMessage.setLink(body); } }); item.getChild(DESCRIPTION) .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentMessage.setDescription(body); } }); item.getChild(PUB_DATE) .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentMessage.setDate(body); } }); try { Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler()); } catch (Exception e) { throw new RuntimeException(e); } return messages; }
@Override public Object parseXml(String xmlString) throws Exception { RootElement rootElement = new RootElement(Tags.submitBike); Element messageHeadingElement = rootElement.getChild(Tags.MessageHeading); Element messageBodyElement = rootElement.getChild(Tags.MessageBody); messageHeadingElement.setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { messageHeading = body; } }); Xml.parse(xmlString, rootElement.getContentHandler()); return messageHeading; }
/** * Get current server UNIX time. * * @param context * @return * @throws SAXException */ public static long getServerTime(Context context) throws SAXException { final long[] serverTime = new long[1]; final RootElement root = new RootElement("Items"); root.getChild("Time") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { serverTime[0] = Long.valueOf(body); } }); final String url = xmlMirror + "Updates.php?type=none"; HttpUriRequest request = new HttpGet(url); HttpClient httpClient = getHttpClient(); execute(request, httpClient, root.getContentHandler(), false); return serverTime[0]; }
/** * Parses the xml String favourites.xml * * @param context the context * @param xml the xml * @return the list´ * @author RayBa * @throws SAXException * @date 05.07.2012 */ public List<Fav> parse(Context context, String xml) throws SAXException { RootElement root = new RootElement("settings"); Element sectionElement = root.getChild("section"); Element entryElement = sectionElement.getChild("entry"); root.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attributes) { favourites = new ArrayList<Fav>(); } }); entryElement.setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { String[] channelInfos = body.split("\\|"); if (channelInfos.length > 1) { currentFav = new Fav(); long id = Long.valueOf(channelInfos[0]); currentFav.id = id; currentFav.name = channelInfos[1]; favourites.add(currentFav); } } }); Xml.parse(xml, root.getContentHandler()); for (int i = 0; i < favourites.size(); i++) { Fav fav = favourites.get(i); fav.position = i + 1; } return favourites; }
@Override protected ContentHandler contentHandler() { cats_ = new PhotomapCategories(); final RootElement root = new RootElement("photomapcategories"); final Element cat = root.getChild("categories").getChild("category"); final Element metaCat = root.getChild("metacategories").getChild("metacategory"); final Listener listener = new Listener(); cat.setStartElementListener(listener.start()); metaCat.setStartElementListener(listener.start()); for (final String n : listener.endListeners().keySet()) { final EndTextElementListener l = listener.endListeners().get(n); cat.getChild(n).setEndTextElementListener(l); metaCat.getChild(n).setEndTextElementListener(l); } // for ... cat.setEndElementListener( new EndElementListener() { public void end() { cats_.addCategory( listener.tag(), listener.name(), listener.description(), listener.ordering()); } // end }); metaCat.setEndElementListener( new EndElementListener() { public void end() { cats_.addMetaCategory( listener.tag(), listener.name(), listener.description(), listener.ordering()); } // end }); return root.getContentHandler(); } // contentHandler
@Override public Collection<cgCache> parse( final InputStream stream, final CancellableHandler progressHandler) throws IOException, ParserException { resetCache(); final RootElement root = new RootElement(namespace, "gpx"); final Element waypoint = root.getChild(namespace, "wpt"); // waypoint - attributes waypoint.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attrs) { try { if (attrs.getIndex("lat") > -1 && attrs.getIndex("lon") > -1) { final String latitude = attrs.getValue("lat"); final String longitude = attrs.getValue("lon"); // latitude and longitude are required attributes, but we export them empty for // waypoints without coordinates if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) { cache.setCoords( new Geopoint(Double.valueOf(latitude), Double.valueOf(longitude))); } } } catch (Exception e) { Log.w("Failed to parse waypoint's latitude and/or longitude."); } } }); // waypoint waypoint.setEndElementListener( new EndElementListener() { @Override public void end() { // try to find geocode somewhere else if (StringUtils.isBlank(cache.getGeocode())) { findGeoCode(name); findGeoCode(desc); findGeoCode(cmt); } // take the name as code, if nothing else is available if (StringUtils.isBlank(cache.getGeocode())) { if (StringUtils.isNotBlank(name)) { cache.setGeocode(name.trim()); } } if (StringUtils.isNotBlank(cache.getGeocode()) && cache.getCoords() != null && ((type == null && sym == null) || StringUtils.contains(type, "geocache") || StringUtils.contains(sym, "geocache"))) { fixCache(cache); cache.setListId(listId); cache.setDetailed(true); createNoteFromGSAKUserdata(); final String geocode = cache.getGeocode(); if (result.contains(geocode)) { Log.w("Duplicate geocode during GPX import: " + geocode); } // modify cache depending on the use case/connector afterParsing(cache); // finally store the cache in the database result.add(geocode); cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); cgData.removeAllFromCache(); showProgressMessage(progressHandler, progressStream.getProgress()); } else if (StringUtils.isNotBlank(cache.getName()) && StringUtils.containsIgnoreCase(type, "waypoint")) { addWaypointToCache(); } resetCache(); } private void addWaypointToCache() { fixCache(cache); if (cache.getName().length() > 2) { final String cacheGeocodeForWaypoint = "GC" + cache.getName().substring(2).toUpperCase(Locale.US); // lookup cache for waypoint in already parsed caches final cgCache cacheForWaypoint = cgData.loadCache(cacheGeocodeForWaypoint, LoadFlags.LOAD_CACHE_OR_DB); if (cacheForWaypoint != null) { final Waypoint waypoint = new Waypoint(cache.getShortdesc(), convertWaypointSym2Type(sym), false); waypoint.setId(-1); waypoint.setGeocode(cacheGeocodeForWaypoint); waypoint.setPrefix(cache.getName().substring(0, 2)); waypoint.setLookup("---"); // there is no lookup code in gpx file waypoint.setCoords(cache.getCoords()); waypoint.setNote(cache.getDescription()); final ArrayList<Waypoint> mergedWayPoints = new ArrayList<Waypoint>(); mergedWayPoints.addAll(cacheForWaypoint.getWaypoints()); final ArrayList<Waypoint> newPoints = new ArrayList<Waypoint>(); newPoints.add(waypoint); Waypoint.mergeWayPoints(newPoints, mergedWayPoints, true); cacheForWaypoint.setWaypoints(newPoints, false); cgData.saveCache(cacheForWaypoint, EnumSet.of(SaveFlag.SAVE_DB)); showProgressMessage(progressHandler, progressStream.getProgress()); } } } }); // waypoint.time waypoint .getChild(namespace, "time") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { try { cache.setHidden(parseDate(body)); } catch (Exception e) { Log.w("Failed to parse cache date", e); } } }); // waypoint.getName() waypoint .getChild(namespace, "name") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { name = body; final String content = body.trim(); cache.setName(content); findGeoCode(cache.getName()); } }); // waypoint.desc waypoint .getChild(namespace, "desc") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { desc = body; cache.setShortdesc(validate(body)); } }); // waypoint.cmt waypoint .getChild(namespace, "cmt") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { cmt = body; cache.setDescription(validate(body)); } }); // waypoint.getType() waypoint .getChild(namespace, "type") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { final String[] content = body.split("\\|"); if (content.length > 0) { type = content[0].toLowerCase(Locale.US).trim(); } } }); // waypoint.sym waypoint .getChild(namespace, "sym") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(final String body) { sym = body.toLowerCase(Locale.US); if (sym.contains("geocache") && sym.contains("found")) { cache.setFound(true); } } }); // waypoint.url waypoint .getChild(namespace, "url") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String url) { final MatcherWrapper matcher = new MatcherWrapper(patternGuid, url); if (matcher.matches()) { final String guid = matcher.group(1); if (StringUtils.isNotBlank(guid)) { cache.setGuid(guid); } } final MatcherWrapper matcherCode = new MatcherWrapper(patternUrlGeocode, url); if (matcherCode.matches()) { String geocode = matcherCode.group(1); cache.setGeocode(geocode); } } }); // for GPX 1.0, cache info comes from waypoint node (so called private children, // for GPX 1.1 from extensions node final Element cacheParent = getCacheParent(waypoint); // GSAK extensions for (String gsakNamespace : GSAK_NS) { final Element gsak = cacheParent.getChild(gsakNamespace, "wptExtension"); gsak.getChild(gsakNamespace, "Watch") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String watchList) { cache.setOnWatchlist(Boolean.valueOf(watchList.trim())); } }); gsak.getChild(gsakNamespace, "UserData").setEndTextElementListener(new UserDataListener(1)); for (int i = 2; i <= 4; i++) { gsak.getChild(gsakNamespace, "User" + i).setEndTextElementListener(new UserDataListener(i)); } } // 3 different versions of the GC schema for (String nsGC : nsGCList) { // waypoints.cache final Element gcCache = cacheParent.getChild(nsGC, "cache"); gcCache.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attrs) { try { if (attrs.getIndex("id") > -1) { cache.setCacheId(attrs.getValue("id")); } if (attrs.getIndex("archived") > -1) { cache.setArchived(attrs.getValue("archived").equalsIgnoreCase("true")); } if (attrs.getIndex("available") > -1) { cache.setDisabled(!attrs.getValue("available").equalsIgnoreCase("true")); } } catch (Exception e) { Log.w("Failed to parse cache attributes."); } } }); // waypoint.cache.getName() gcCache .getChild(nsGC, "name") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String cacheName) { cache.setName(validate(cacheName)); } }); // waypoint.cache.getOwner() gcCache .getChild(nsGC, "owner") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String ownerUserId) { cache.setOwnerUserId(validate(ownerUserId)); } }); // waypoint.cache.getOwner() gcCache .getChild(nsGC, "placed_by") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String ownerDisplayName) { cache.setOwnerDisplayName(validate(ownerDisplayName)); } }); // waypoint.cache.getType() gcCache .getChild(nsGC, "type") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { cache.setType(CacheType.getByPattern(validate(body))); } }); // waypoint.cache.container gcCache .getChild(nsGC, "container") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { cache.setSize(CacheSize.getById(validate(body))); } }); // waypoint.cache.getAttributes() // @see issue #299 // <groundspeak:attributes> // <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute> // <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute> // where inc = 0 => _no, inc = 1 => _yes // IDs see array CACHE_ATTRIBUTES final Element gcAttributes = gcCache.getChild(nsGC, "attributes"); // waypoint.cache.attribute final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute"); gcAttribute.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attrs) { try { if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) { int attributeId = Integer.parseInt(attrs.getValue("id")); boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0; String internalId = CacheAttributeTranslator.getInternalId(attributeId, attributeActive); if (internalId != null) { cache.getAttributes().add(internalId); } } } catch (NumberFormatException e) { // nothing } } }); // waypoint.cache.getDifficulty() gcCache .getChild(nsGC, "difficulty") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { try { cache.setDifficulty(Float.parseFloat(body)); } catch (NumberFormatException e) { Log.w("Failed to parse difficulty", e); } } }); // waypoint.cache.getTerrain() gcCache .getChild(nsGC, "terrain") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { try { cache.setTerrain(Float.parseFloat(body)); } catch (NumberFormatException e) { Log.w("Failed to parse terrain", e); } } }); // waypoint.cache.country gcCache .getChild(nsGC, "country") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String country) { if (StringUtils.isBlank(cache.getLocation())) { cache.setLocation(validate(country)); } else { cache.setLocation(cache.getLocation() + ", " + country.trim()); } } }); // waypoint.cache.state gcCache .getChild(nsGC, "state") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String state) { String trimmedState = state.trim(); if (StringUtils.isNotEmpty(trimmedState)) { // state can be completely empty if (StringUtils.isBlank(cache.getLocation())) { cache.setLocation(validate(state)); } else { cache.setLocation(trimmedState + ", " + cache.getLocation()); } } } }); // waypoint.cache.encoded_hints gcCache .getChild(nsGC, "encoded_hints") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String encoded) { cache.setHint(validate(encoded)); } }); gcCache .getChild(nsGC, "short_description") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String shortDesc) { cache.setShortdesc(validate(shortDesc)); } }); gcCache .getChild(nsGC, "long_description") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String desc) { cache.setDescription(validate(desc)); } }); // waypoint.cache.travelbugs final Element gcTBs = gcCache.getChild(nsGC, "travelbugs"); // waypoint.cache.travelbug final Element gcTB = gcTBs.getChild(nsGC, "travelbug"); // waypoint.cache.travelbugs.travelbug gcTB.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attrs) { trackable = new Trackable(); try { if (attrs.getIndex("ref") > -1) { trackable.setGeocode(attrs.getValue("ref")); } } catch (Exception e) { // nothing } } }); gcTB.setEndElementListener( new EndElementListener() { @Override public void end() { if (StringUtils.isNotBlank(trackable.getGeocode()) && StringUtils.isNotBlank(trackable.getName())) { if (cache.getInventory() == null) { cache.setInventory(new ArrayList<Trackable>()); } cache.getInventory().add(trackable); } } }); // waypoint.cache.travelbugs.travelbug.getName() gcTB.getChild(nsGC, "name") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String tbName) { trackable.setName(validate(tbName)); } }); // waypoint.cache.logs final Element gcLogs = gcCache.getChild(nsGC, "logs"); // waypoint.cache.log final Element gcLog = gcLogs.getChild(nsGC, "log"); gcLog.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attrs) { log = new LogEntry("", 0, LogType.UNKNOWN, ""); try { if (attrs.getIndex("id") > -1) { log.id = Integer.parseInt(attrs.getValue("id")); } } catch (Exception e) { // nothing } } }); gcLog.setEndElementListener( new EndElementListener() { @Override public void end() { if (log.type != LogType.UNKNOWN) { cache.getLogs().add(log); } } }); // waypoint.cache.logs.log.date gcLog .getChild(nsGC, "date") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { try { log.date = parseDate(body).getTime(); } catch (Exception e) { Log.w("Failed to parse log date", e); } } }); // waypoint.cache.logs.log.getType() gcLog .getChild(nsGC, "type") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { final String logType = validate(body); log.type = LogType.getByType(logType); } }); // waypoint.cache.logs.log.finder gcLog .getChild(nsGC, "finder") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String finderName) { log.author = validate(finderName); } }); // waypoint.cache.logs.log.text gcLog .getChild(nsGC, "text") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String logText) { log.log = validate(logText); } }); } try { progressStream = new ProgressInputStream(stream); Xml.parse(progressStream, Xml.Encoding.UTF_8, root.getContentHandler()); return cgData.loadCaches(result, EnumSet.of(LoadFlag.LOAD_DB_MINIMAL)); } catch (SAXException e) { Log.w("Cannot parse .gpx file as GPX " + version + ": could not parse XML - ", e); throw new ParserException( "Cannot parse .gpx file as GPX " + version + ": could not parse XML", e); } }
public List<Show> parse(InputStream inputStream) { try { InputSource inputSource = new InputSource(inputStream); XMLReader xmlReader = XMLReaderFactory.createXMLReader("org.xmlpull.v1.sax2.Driver"); RootElement rootElement = new RootElement("Data"); Element seriesElement = rootElement.getChild("Series"); seriesElement.setStartElementListener( new StartElementListener() { public void start(Attributes attributes) { Log.i(TAG, "Begin parsing show"); current = new Show(); } }); seriesElement.setEndElementListener( new EndElementListener() { public void end() { Log.i(TAG, "End parsing show"); parsed.add(current); current = null; } }); Element idElement = seriesElement.requireChild("id"); idElement.setEndTextElementListener( new EndTextElementListener() { public void end(String body) { int id = Integer.parseInt(body); Log.i(TAG, String.format("Parsed ID: %d", id)); current.setId(id); } }); Element nameElement = seriesElement.requireChild("SeriesName"); nameElement.setEndTextElementListener( new EndTextElementListener() { public void end(String body) { Log.i(TAG, String.format("Parsed name: %s", body)); current.setName(body); } }); Element languageElement = seriesElement.getChild("language"); languageElement.setEndTextElementListener( new EndTextElementListener() { public void end(String body) { Log.i(TAG, String.format("Parsed language: %s", body)); current.setLanguage(body); } }); Element overviewElement = seriesElement.getChild("Overview"); overviewElement.setEndTextElementListener( new EndTextElementListener() { public void end(String body) { Log.i(TAG, String.format("Parsed overview: %s", body)); current.setOverview(body); } }); Element firstAiredElement = seriesElement.getChild("FirstAired"); firstAiredElement.setEndTextElementListener( new EndTextElementListener() { public void end(String body) { try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US); Date firstAired = df.parse(body); Log.i(TAG, String.format("Parsed first aired date: %s", firstAired.toString())); current.setFirstAired(firstAired); } catch (ParseException e) { Log.w(TAG, "Error parsing first aired date: " + e.toString()); current.setFirstAired(null); } } }); xmlReader.setContentHandler(rootElement.getContentHandler()); current = null; parsed = new LinkedList<Show>(); xmlReader.parse(inputSource); return parsed; } catch (SAXException e) { Log.w(TAG, "SAXException - parse: " + e.toString()); return null; } catch (IOException e) { Log.w(TAG, "IOException - parse: " + e.toString()); return null; } }
/** @return 返回设置好处理机制的rootElement */ private RootElement getRootElement() { /* rootElement代表着根节点,参数为根节点的tagName */ RootElement rootElement = new RootElement("data"); /* * 获取一类子节点,并为其设置相应的事件 这里需要注意,虽然我们只设置了一次beauty的事件,但是我们文档中根节点下的所有 * beauty却都可以触发这个事件。 */ Element checkElement = rootElement.getChild("state"); checkElement.setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { if ("Y".equals(body)) { videos = new ArrayList<VideoBean>(); } else { videos = null; } } }); Element parambufElement = rootElement.getChild("parambuf"); Element infoElement = parambufElement.getChild("info"); // 读到元素开始位置时触发,如读到<beauty>时 infoElement.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attributes) { // Log.i("通知", "start"); videoBean = new VideoBean(); } }); // 读到元素结束位置时触发,如读到</beauty>时 infoElement.setEndElementListener( new EndElementListener() { @Override public void end() { videos.add(videoBean); } }); Element vidElement = infoElement.getChild("vid"); // 读到文本的末尾时触发,这里的body即为文本的内容部分 vidElement.setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { videoBean.setvId(body); } }); Element nameElement = infoElement.getChild("name"); nameElement.setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { videoBean.setName(body); } }); Element stateElement = infoElement.getChild("state"); stateElement.setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { videoBean.setState(body); } }); return rootElement; }
public static ArrayList<ContentProviderOperation> parseEpisodes( String url, String showId, final long showAirtime, Context context) throws SAXException { RootElement root = new RootElement("Data"); Element episode = root.getChild("Episode"); final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); final HashSet<Long> episodeIDs = DBUtils.getEpisodeIDsForShow(showId, context); final HashSet<Long> existingSeasonIDs = DBUtils.getSeasonIDsForShow(showId, context); final HashSet<Long> updatedSeasonIDs = new HashSet<Long>(); final ContentValues values = new ContentValues(); // set handlers for elements we want to react to episode.setEndElementListener( new EndElementListener() { public void end() { // add insert/update op for episode batch.add( DBUtils.buildEpisodeOp( values, !episodeIDs.contains(values.getAsLong(Episodes._ID)))); long seasonid = values.getAsLong(Seasons.REF_SEASON_ID); if (!updatedSeasonIDs.contains(seasonid)) { // add insert/update op for season batch.add(DBUtils.buildSeasonOp(values, !existingSeasonIDs.contains(seasonid))); updatedSeasonIDs.add(values.getAsLong(Seasons.REF_SEASON_ID)); } values.clear(); } }); episode .getChild("id") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Episodes._ID, body.trim()); } }); episode .getChild("EpisodeNumber") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Episodes.NUMBER, body.trim()); } }); episode .getChild("SeasonNumber") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Episodes.SEASON, body.trim()); } }); episode .getChild("DVD_episodenumber") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Episodes.DVDNUMBER, body.trim()); } }); episode .getChild("FirstAired") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { long episodeAirTime = Utils.buildEpisodeAirtime(body, showAirtime); values.put(Episodes.FIRSTAIREDMS, episodeAirTime); values.put(Episodes.FIRSTAIRED, body.trim()); } }); episode .getChild("EpisodeName") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Episodes.TITLE, body.trim()); } }); episode .getChild("Overview") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Episodes.OVERVIEW, body.trim()); } }); episode .getChild("seasonid") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Seasons.REF_SEASON_ID, body.trim()); } }); episode .getChild("seriesid") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Shows.REF_SHOW_ID, body.trim()); } }); episode .getChild("Director") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Episodes.DIRECTORS, body.trim()); } }); episode .getChild("GuestStars") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Episodes.GUESTSTARS, body.trim()); } }); episode .getChild("Writer") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Episodes.WRITERS, body.trim()); } }); episode .getChild("Rating") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Episodes.RATING, body.trim()); } }); episode .getChild("filename") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { values.put(Episodes.IMAGE, body.trim()); } }); HttpUriRequest request = new HttpGet(url); HttpClient httpClient = getHttpClient(); execute(request, httpClient, root.getContentHandler(), true); return batch; }
/** * Parses the xml downloaded from the given url into a {@link Series} object. Downloads the poster * if there is one. * * @param url * @param context * @return the show wrapped in a {@link Series} object * @throws SAXException */ public static Series parseShow(String url, final Context context) throws SAXException { final Series currentShow = new Series(); RootElement root = new RootElement("Data"); Element show = root.getChild("Series"); // set handlers for elements we want to react to show.getChild("id") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setId(body.trim()); } }); show.getChild("Language") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setLanguage(body.trim()); } }); show.getChild("SeriesName") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setSeriesName(body.trim()); } }); show.getChild("Overview") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setOverview(body.trim()); } }); show.getChild("Actors") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setActors(body.trim()); } }); show.getChild("Airs_DayOfWeek") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setAirsDayOfWeek(body.trim()); } }); show.getChild("Airs_Time") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setAirsTime(Utils.parseTimeToMilliseconds(body.trim())); } }); show.getChild("FirstAired") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setFirstAired(body.trim()); } }); show.getChild("Genre") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setGenres(body.trim()); } }); show.getChild("Network") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setNetwork(body.trim()); } }); show.getChild("Rating") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setRating(body.trim()); } }); show.getChild("Runtime") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setRuntime(body.trim()); } }); show.getChild("Status") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { final String status = body.trim(); if (status.length() == 10) { currentShow.setStatus(1); } else if (status.length() == 5) { currentShow.setStatus(0); } else { currentShow.setStatus(-1); } } }); show.getChild("ContentRating") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setContentRating(body.trim()); } }); show.getChild("poster") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { String posterurl = body.trim(); currentShow.setPoster(posterurl); if (posterurl.length() != 0) { fetchArt(posterurl, true, context); } } }); show.getChild("IMDB_ID") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.setImdbId(body.trim()); } }); HttpUriRequest request = new HttpGet(url); HttpClient httpClient = getHttpClient(); execute(request, httpClient, root.getContentHandler(), false); return currentShow; }
/** * Search for shows which include a certain keyword in their title. Dependent on the TheTVDB * search algorithms. * * @param title * @return a List with SearchResult objects, max 100 * @throws SAXException * @throws IOException */ public static List<SearchResult> searchShow(String title, Context context) throws IOException, SAXException { String language = getTheTVDBLanguage(context); URL url; try { url = new URL( xmlMirror + "GetSeries.php?seriesname=" + URLEncoder.encode(title, "UTF-8") + (language != null ? "&language=" + language : "")); } catch (Exception e) { throw new RuntimeException(e); } final List<SearchResult> series = new ArrayList<SearchResult>(); final SearchResult currentShow = new SearchResult(); RootElement root = new RootElement("Data"); Element item = root.getChild("Series"); // set handlers for elements we want to react to item.setEndElementListener( new EndElementListener() { public void end() { series.add(currentShow.copy()); } }); item.getChild("id") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.tvdbid = body; } }); item.getChild("SeriesName") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.title = body.trim(); } }); item.getChild("Overview") .setEndTextElementListener( new EndTextElementListener() { public void end(String body) { currentShow.overview = body.trim(); } }); URLConnection connection = url.openConnection(); connection.setConnectTimeout(25000); connection.setReadTimeout(90000); InputStream in = connection.getInputStream(); try { Xml.parse(in, Xml.Encoding.UTF_8, root.getContentHandler()); } catch (Exception e) { throw new IOException(); } in.close(); return series; }
public long parse(final InputStream stream, Handler handlerIn) { handler = handlerIn; final RootElement root = new RootElement(namespace, "gpx"); final Element waypoint = root.getChild(namespace, "wpt"); // waypoint - attributes waypoint.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attrs) { try { if (attrs.getIndex("lat") > -1) { cache.latitude = new Double(attrs.getValue("lat")); } if (attrs.getIndex("lon") > -1) { cache.longitude = new Double(attrs.getValue("lon")); } } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse waypoint's latitude and/or longitude."); } } }); // waypoint waypoint.setEndElementListener( new EndElementListener() { @Override public void end() { if (cache.geocode == null || cache.geocode.length() == 0) { // try to find geocode somewhere else findGeoCode(name); findGeoCode(desc); findGeoCode(cmt); } if (cache.geocode != null && cache.geocode.length() > 0 && cache.latitude != null && cache.longitude != null && ((type == null && sym == null) || (type != null && type.indexOf("geocache") > -1) || (sym != null && sym.indexOf("geocache") > -1))) { fixCache(cache); cache.reason = listId; cache.detailed = true; app.addCacheToSearch(search, cache); } showFinishedMessage(handler, search); type = null; sym = null; name = null; desc = null; cmt = null; cache = null; cache = new cgCache(); } }); // waypoint.time waypoint .getChild(namespace, "time") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { try { cache.hidden = parseDate(body); } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse cache date: " + e.toString()); } } }); // waypoint.name waypoint .getChild(namespace, "name") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { name = body; final String content = body.trim(); cache.name = content; findGeoCode(cache.name); findGeoCode(cache.description); } }); // waypoint.desc waypoint .getChild(namespace, "desc") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { desc = body; cache.shortdesc = validate(body); } }); // waypoint.cmt waypoint .getChild(namespace, "cmt") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { cmt = body; cache.description = validate(body); } }); // waypoint.type waypoint .getChild(namespace, "type") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { final String[] content = body.split("\\|"); if (content.length > 0) { type = content[0].toLowerCase().trim(); } } }); // waypoint.sym waypoint .getChild(namespace, "sym") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { body = body.toLowerCase(); sym = body; if (body.indexOf("geocache") != -1 && body.indexOf("found") != -1) { cache.found = true; } } }); // waypoint.url waypoint .getChild(namespace, "url") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String url) { final Matcher matcher = patternGuid.matcher(url); if (matcher.matches()) { String guid = matcher.group(1); if (guid.length() > 0) { cache.guid = guid; } } } }); // for GPX 1.0, cache info comes from waypoint node (so called private children, // for GPX 1.1 from extensions node final Element cacheParent = getCacheParent(waypoint); for (String nsGC : nsGCList) { // waypoints.cache final Element gcCache = cacheParent.getChild(nsGC, "cache"); gcCache.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attrs) { try { if (attrs.getIndex("id") > -1) { cache.cacheid = attrs.getValue("id"); } if (attrs.getIndex("archived") > -1) { cache.archived = attrs.getValue("archived").equalsIgnoreCase("true"); } if (attrs.getIndex("available") > -1) { cache.disabled = !attrs.getValue("available").equalsIgnoreCase("true"); } } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse cache attributes."); } } }); // waypoint.cache.name gcCache .getChild(nsGC, "name") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String cacheName) { cache.name = validate(cacheName); } }); // waypoint.cache.owner gcCache .getChild(nsGC, "owner") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String cacheOwner) { cache.owner = validate(cacheOwner); } }); // waypoint.cache.type gcCache .getChild(nsGC, "type") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { setType(validate(body.toLowerCase())); } }); // waypoint.cache.container gcCache .getChild(nsGC, "container") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { cache.size = validate(body.toLowerCase()); } }); // waypoint.cache.attributes // @see issue #299 // <groundspeak:attributes> // <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute> // <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute> // where inc = 0 => _no, inc = 1 => _yes // IDs see array CACHE_ATTRIBUTES final Element gcAttributes = gcCache.getChild(nsGC, "attributes"); // waypoint.cache.attribute final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute"); gcAttribute.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attrs) { try { if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) { int attributeId = Integer.parseInt(attrs.getValue("id")); boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0; String internalId = CacheAttributeTranslator.getInternalId(attributeId, attributeActive); if (internalId != null) { if (cache.attributes == null) { cache.attributes = new ArrayList<String>(); } cache.attributes.add(internalId); } } } catch (NumberFormatException e) { // nothing } } }); // waypoint.cache.difficulty gcCache .getChild(nsGC, "difficulty") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { try { cache.difficulty = new Float(body); } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse difficulty: " + e.toString()); } } }); // waypoint.cache.terrain gcCache .getChild(nsGC, "terrain") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { try { cache.terrain = new Float(body); } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse terrain: " + e.toString()); } } }); // waypoint.cache.country gcCache .getChild(nsGC, "country") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String country) { if (cache.location == null || cache.location.length() == 0) { cache.location = validate(country); } else { cache.location = cache.location + ", " + country.trim(); } } }); // waypoint.cache.state gcCache .getChild(nsGC, "state") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String state) { if (cache.location == null || cache.location.length() == 0) { cache.location = validate(state); } else { cache.location = state.trim() + ", " + cache.location; } } }); // waypoint.cache.encoded_hints gcCache .getChild(nsGC, "encoded_hints") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String encoded) { cache.hint = validate(encoded); } }); gcCache .getChild(nsGC, "short_description") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String shortDesc) { cache.shortdesc = validate(shortDesc); } }); gcCache .getChild(nsGC, "long_description") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String desc) { cache.description = validate(desc); } }); // waypoint.cache.travelbugs final Element gcTBs = gcCache.getChild(nsGC, "travelbugs"); // waypoint.cache.travelbugs.travelbug gcTBs .getChild(nsGC, "travelbug") .setStartElementListener( new StartElementListener() { @Override public void start(Attributes attrs) { trackable = new cgTrackable(); try { if (attrs.getIndex("ref") > -1) { trackable.geocode = attrs.getValue("ref").toUpperCase(); } } catch (Exception e) { // nothing } } }); // waypoint.cache.travelbug final Element gcTB = gcTBs.getChild(nsGC, "travelbug"); gcTB.setEndElementListener( new EndElementListener() { @Override public void end() { if (trackable.geocode != null && trackable.geocode.length() > 0 && trackable.name != null && trackable.name.length() > 0) { if (cache.inventory == null) { cache.inventory = new ArrayList<cgTrackable>(); } cache.inventory.add(trackable); } } }); // waypoint.cache.travelbugs.travelbug.name gcTB.getChild(nsGC, "name") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String tbName) { trackable.name = validate(tbName); } }); // waypoint.cache.logs final Element gcLogs = gcCache.getChild(nsGC, "logs"); // waypoint.cache.log final Element gcLog = gcLogs.getChild(nsGC, "log"); gcLog.setStartElementListener( new StartElementListener() { @Override public void start(Attributes attrs) { log = new cgLog(); try { if (attrs.getIndex("id") > -1) { log.id = Integer.parseInt(attrs.getValue("id")); } } catch (Exception e) { // nothing } } }); gcLog.setEndElementListener( new EndElementListener() { @Override public void end() { if (log.log != null && log.log.length() > 0) { if (cache.logs == null) { cache.logs = new ArrayList<cgLog>(); } cache.logs.add(log); } } }); // waypoint.cache.logs.log.date gcLog .getChild(nsGC, "date") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { try { log.date = parseDate(body).getTime(); } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse log date: " + e.toString()); } } }); // waypoint.cache.logs.log.type gcLog .getChild(nsGC, "type") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { final String logType = validate(body).toLowerCase(); if (cgBase.logTypes0.containsKey(logType)) { log.type = cgBase.logTypes0.get(logType); } else { log.type = cgBase.LOG_NOTE; } } }); // waypoint.cache.logs.log.finder gcLog .getChild(nsGC, "finder") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String finderName) { log.author = validate(finderName); } }); // waypoint.cache.logs.log.text gcLog .getChild(nsGC, "text") .setEndTextElementListener( new EndTextElementListener() { @Override public void end(String logText) { log.log = validate(logText); } }); } boolean parsed = false; try { Xml.parse(stream, Xml.Encoding.UTF_8, root.getContentHandler()); parsed = true; } catch (IOException e) { Log.e(cgSettings.tag, "Cannot parse .gpx file as GPX " + version + ": could not read file!"); } catch (SAXException e) { Log.e( cgSettings.tag, "Cannot parse .gpx file as GPX " + version + ": could not parse XML - " + e.toString()); } return parsed ? search.getCurrentId() : 0L; }