Java Code Examples for org.xmlpull.v1.XmlPullParser#END_DOCUMENT

The following examples show how to use org.xmlpull.v1.XmlPullParser#END_DOCUMENT . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XmlUtils.java    From AcDisplay with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Read a HashSet object from an XmlPullParser. The XML data could previously
 * have been generated by writeSetXml(). The XmlPullParser must be positioned
 * <em>after</em> the tag that begins the set.
 *
 * @param parser The XmlPullParser from which to read the set data.
 * @param endTag Name of the tag that will end the set, usually "set".
 * @param name   An array of one string, used to return the name attribute
 *               of the set's tag.
 * @return HashSet The newly generated set.
 * @throws XmlPullParserException
 * @throws java.io.IOException
 * @see #readSetXml
 */
private static HashSet readThisSetXml(XmlPullParser parser, String endTag, String[] name,
                                      ReadMapCallback callback)
        throws XmlPullParserException, java.io.IOException {
    HashSet set = new HashSet();

    int eventType = parser.getEventType();
    do {
        if (eventType == XmlPullParser.START_TAG) {
            Object val = readThisValueXml(parser, name, callback);
            set.add(val);
            //System.out.println("Adding to set: " + val);
        } else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getName().equals(endTag)) {
                return set;
            }
            throw new XmlPullParserException(
                    "Expected " + endTag + " end tag at: " + parser.getName());
        }
        eventType = parser.next();
    } while (eventType != XmlPullParser.END_DOCUMENT);

    throw new XmlPullParserException(
            "Document ended before " + endTag + " end tag");
}
 
Example 2
Source File: MusicFoldersParser.java    From Audinaut with GNU General Public License v3.0 6 votes vote down vote up
public List<MusicFolder> parse(InputStream inputStream) throws Exception {
    init(inputStream);

    List<MusicFolder> result = new ArrayList<>();
    int eventType;
    do {
        eventType = nextParseEvent();
        if (eventType == XmlPullParser.START_TAG) {
            String tag = getElementName();
            if ("musicFolder".equals(tag)) {
                String id = get("id");
                String name = get("name");
                result.add(new MusicFolder(id, name));
            } else if ("error".equals(tag)) {
                handleError();
            }
        }
    } while (eventType != XmlPullParser.END_DOCUMENT);

    validate();

    return result;
}
 
Example 3
Source File: XmlUtils.java    From JobSchedulerCompat with MIT License 6 votes vote down vote up
private static HashMap<String, ?> readThisMapXml(XmlPullParser parser, String endTag, String[] name)
        throws XmlPullParserException, IOException {
    HashMap<String, Object> map = new HashMap<>();

    int eventType = parser.getEventType();
    do {
        if (eventType == XmlPullParser.START_TAG) {
            Object val = readThisValueXml(parser, name);
            map.put(name[0], val);
        } else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getName().equals(endTag)) {
                return map;
            }
            throw new XmlPullParserException("Expected " + endTag + " end tag at: " + parser.getName());
        }
        eventType = parser.next();
    } while (eventType != XmlPullParser.END_DOCUMENT);

    throw new XmlPullParserException("Document ended before " + endTag + " end tag");
}
 
Example 4
Source File: ThemedColorStateList.java    From revolution-irc with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a ColorStateList from an XML document using given a set of
 * {@link Resources} and a {@link Resources.Theme}.
 *
 * @param r Resources against which the ColorStateList should be inflated.
 * @param parser Parser for the XML document defining the ColorStateList.
 * @param theme Optional theme to apply to the color state list, may be
 *              {@code null}.
 * @return A new color state list.
 */
@NonNull
public static ThemedColorStateList createFromXml(
        @NonNull Resources r, @NonNull XmlPullParser parser, @Nullable Resources.Theme theme)
        throws XmlPullParserException, IOException {
    final AttributeSet attrs = Xml.asAttributeSet(parser);

    int type;
    while ((type = parser.next()) != XmlPullParser.START_TAG
            && type != XmlPullParser.END_DOCUMENT) {
        // Seek parser to start tag.
    }

    if (type != XmlPullParser.START_TAG) {
        throw new XmlPullParserException("No start tag found");
    }

    return createFromXmlInner(r, parser, attrs, theme);
}
 
Example 5
Source File: LauncherBackupHelper.java    From Trebuchet with GNU General Public License v3.0 6 votes vote down vote up
private ArrayList<Intent> parseIntents(int xml_res) {
    ArrayList<Intent> intents = new ArrayList<Intent>();
    XmlResourceParser parser = mContext.getResources().getXml(xml_res);
    try {
        DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
        final int depth = parser.getDepth();
        int type;
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
            if (type != XmlPullParser.START_TAG) {
                continue;
            } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
                final String uri = DefaultLayoutParser.getAttributeValue(
                        parser, DefaultLayoutParser.ATTR_URI);
                intents.add(Intent.parseUri(uri, 0));
            }
        }
    } catch (URISyntaxException | XmlPullParserException | IOException e) {
        Log.e(TAG, "Unable to parse " + xml_res, e);
    } finally {
        parser.close();
    }
    return intents;
}
 
Example 6
Source File: XmlTvParser.java    From androidtv-sample-inputs with Apache License 2.0 6 votes vote down vote up
private static TvListing parseTvListings(XmlPullParser parser)
        throws IOException, XmlPullParserException, ParseException {
    List<Channel> channels = new ArrayList<>();
    List<Program> programs = new ArrayList<>();
    while (parser.next() != XmlPullParser.END_DOCUMENT) {
        if (parser.getEventType() == XmlPullParser.START_TAG
                && TAG_CHANNEL.equalsIgnoreCase(parser.getName())) {
            channels.add(parseChannel(parser));
        }
        if (parser.getEventType() == XmlPullParser.START_TAG
                && TAG_PROGRAM.equalsIgnoreCase(parser.getName())) {
            programs.add(parseProgram(parser));
        }
    }
    return new TvListing(channels, programs);
}
 
Example 7
Source File: Rss2Parser.java    From PkRSS with Apache License 2.0 6 votes vote down vote up
/**
 * Pulls an image URL from an encoded String.
 *
 * @param encoded The String which to extract an image URL from.
 * @return The first image URL found on the encoded String. May return an
 * empty String if none were found.
 */
private String pullImageLink(String encoded) {
	try {
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		XmlPullParser xpp = factory.newPullParser();

		xpp.setInput(new StringReader(encoded));
		int eventType = xpp.getEventType();
		while (eventType != XmlPullParser.END_DOCUMENT) {
			if (eventType == XmlPullParser.START_TAG && "img".equals(xpp.getName())) {
				int count = xpp.getAttributeCount();
				for (int x = 0; x < count; x++) {
					if (xpp.getAttributeName(x).equalsIgnoreCase("src"))
						return pattern.matcher(xpp.getAttributeValue(x)).replaceAll("");
				}
			}
			eventType = xpp.next();
		}
	}
	catch (Exception e) {
		log(TAG, "Error pulling image link from description!\n" + e.getMessage(), Log.WARN);
	}

	return "";
}
 
Example 8
Source File: AliasActivity.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private Intent parseAlias(XmlPullParser parser)
        throws XmlPullParserException, IOException {
    AttributeSet attrs = Xml.asAttributeSet(parser);
    
    Intent intent = null;
    
    int type;
    while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
            && type != XmlPullParser.START_TAG) {
    }
    
    String nodeName = parser.getName();
    if (!"alias".equals(nodeName)) {
        throw new RuntimeException(
                "Alias meta-data must start with <alias> tag; found"
                + nodeName + " at " + parser.getPositionDescription());
    }
    
    int outerDepth = parser.getDepth();
    while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
           && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
        if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
            continue;
        }

        nodeName = parser.getName();
        if ("intent".equals(nodeName)) {
            Intent gotIntent = Intent.parseIntent(getResources(), parser, attrs);
            if (intent == null) intent = gotIntent;
        } else {
            XmlUtils.skipCurrentTag(parser);
        }
    }
    
    return intent;
}
 
Example 9
Source File: ColorStateListUtils.java    From timecat with Apache License 2.0 5 votes vote down vote up
static ColorStateList inflateColorStateList(Context context, XmlPullParser parser, AttributeSet attrs) throws IOException, XmlPullParserException {
    final int innerDepth = parser.getDepth() + 1;
    int depth;
    int type;

    LinkedList<int[]> stateList = new LinkedList<>();
    LinkedList<Integer> colorList = new LinkedList<>();

    while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && ((depth = parser.getDepth()) >= innerDepth || type != XmlPullParser.END_TAG)) {
        if (type != XmlPullParser.START_TAG || depth > innerDepth || !parser.getName().equals("item")) {
            continue;
        }

        TypedArray a1 = context.obtainStyledAttributes(attrs, new int[]{android.R.attr.color});
        final int value = a1.getResourceId(0, Color.MAGENTA);
        final int baseColor = value == Color.MAGENTA ? Color.MAGENTA : ThemeUtils.replaceColorById(context, value);
        a1.recycle();
        TypedArray a2 = context.obtainStyledAttributes(attrs, new int[]{android.R.attr.alpha});
        final float alphaMod = a2.getFloat(0, 1.0f);
        a2.recycle();
        colorList.add(alphaMod != 1.0f ? ColorUtils.setAlphaComponent(baseColor, Math.round(Color.alpha(baseColor) * alphaMod)) : baseColor);

        stateList.add(extractStateSet(attrs));
    }

    if (stateList.size() > 0 && stateList.size() == colorList.size()) {
        int[] colors = new int[colorList.size()];
        for (int i = 0; i < colorList.size(); i++) {
            colors[i] = colorList.get(i);
        }
        return new ColorStateList(stateList.toArray(new int[stateList.size()][]), colors);
    }
    return null;
}
 
Example 10
Source File: PullSOAPActionProcessorImpl.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
protected ActionException readFaultElement(XmlPullParser xpp) throws Exception {
    // We're in the "Fault" tag

    String errorCode = null;
    String errorDescription = null;

    XmlPullParserUtils.searchTag(xpp, "UPnPError");

    int event;
    do {
        event = xpp.next();
        if (event == XmlPullParser.START_TAG) {
            String tag = xpp.getName();
            if (tag.equals("errorCode")) {
                errorCode = xpp.nextText();
            } else if (tag.equals("errorDescription")) {
                errorDescription = xpp.nextText();
            }
        }
    }
    while (event != XmlPullParser.END_DOCUMENT && (event != XmlPullParser.END_TAG || !xpp.getName().equals("UPnPError")));

    if (errorCode != null) {
        try {
            int numericCode = Integer.valueOf(errorCode);
            ErrorCode standardErrorCode = ErrorCode.getByCode(numericCode);
            if (standardErrorCode != null) {
                log.fine("Reading fault element: " + standardErrorCode.getCode() + " - " + errorDescription);
                return new ActionException(standardErrorCode, errorDescription, false);
            } else {
                log.fine("Reading fault element: " + numericCode + " - " + errorDescription);
                return new ActionException(numericCode, errorDescription);
            }
        } catch (NumberFormatException ex) {
            throw new RuntimeException("Error code was not a number");
        }
    }

    throw new RuntimeException("Received fault element but no error code");
}
 
Example 11
Source File: PackageParser.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private boolean parseAllMetaData(Resources res,
        XmlPullParser parser, AttributeSet attrs, String tag,
        Component outInfo, String[] outError)
        throws XmlPullParserException, IOException {
    int outerDepth = parser.getDepth();
    int type;
    while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
           && (type != XmlPullParser.END_TAG
                   || parser.getDepth() > outerDepth)) {
        if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
            continue;
        }

        if (parser.getName().equals("meta-data")) {
            if ((outInfo.metaData=parseMetaData(res, parser, attrs,
                    outInfo.metaData, outError)) == null) {
                return false;
            }
        } else {
            if (!RIGID_PARSER) {
                Slog.w(TAG, "Unknown element under " + tag + ": "
                        + parser.getName() + " at " + mArchiveSourcePath + " "
                        + parser.getPositionDescription());
                XmlUtils.skipCurrentTag(parser);
                continue;
            } else {
                outError[0] = "Bad element under " + tag + ": " + parser.getName();
                return false;
            }
        }
    }
    return true;
}
 
Example 12
Source File: XmlBackup.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
public XmlBackupItem getNext() throws IOException, XmlPullParserException {
  while (parser.next() != XmlPullParser.END_DOCUMENT) {
    if (parser.getEventType() != XmlPullParser.START_TAG) {
      continue;
    }

    String name = parser.getName();

    if (!name.equalsIgnoreCase("sms")) {
      continue;
    }

    int attributeCount = parser.getAttributeCount();

    if (attributeCount <= 0) {
      continue;
    }

    XmlBackupItem item = new XmlBackupItem();

    for (int i=0;i<attributeCount;i++) {
      String attributeName = parser.getAttributeName(i);

      if      (attributeName.equals(PROTOCOL      )) item.protocol      = Integer.parseInt(parser.getAttributeValue(i));
      else if (attributeName.equals(ADDRESS       )) item.address       = parser.getAttributeValue(i);
      else if (attributeName.equals(DATE          )) item.date          = Long.parseLong(parser.getAttributeValue(i));
      else if (attributeName.equals(TYPE          )) item.type          = Integer.parseInt(parser.getAttributeValue(i));
      else if (attributeName.equals(SUBJECT       )) item.subject       = parser.getAttributeValue(i);
      else if (attributeName.equals(BODY          )) item.body          = parser.getAttributeValue(i);
      else if (attributeName.equals(SERVICE_CENTER)) item.serviceCenter = parser.getAttributeValue(i);
      else if (attributeName.equals(READ          )) item.read          = Integer.parseInt(parser.getAttributeValue(i));
      else if (attributeName.equals(STATUS        )) item.status        = Integer.parseInt(parser.getAttributeValue(i));
    }

    return item;
  }

  return null;
}
 
Example 13
Source File: ManifestParser.java    From Neptune with Apache License 2.0 5 votes vote down vote up
/**
 * 解析Activity、Service、Recevier等组件节点
 */
private ComponentBean parseComponent(XmlResourceParser parser) throws IOException, XmlPullParserException {
    ComponentBean bean = new ComponentBean();

    String name = parser.getAttributeValue(ANDROID_RESOURCES, "name");
    bean.className = buildClassName(pkg, name);

    int outerDepth = parser.getDepth();
    int type;
    while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
            && (type != XmlPullParser.END_TAG
            || parser.getDepth() > outerDepth)) {
        if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
            continue;
        }

        String tagName = parser.getName();
        if (tagName.equals("intent-filter")) {
            IntentFilter intentFilter = parseIntent(parser);
            if (intentFilter != null) {
                bean.intentFilters.add(intentFilter);
            }
        }
    }

    return bean;
}
 
Example 14
Source File: RetainedFragment.java    From coursera-android with MIT License 5 votes vote down vote up
private List<String> parseXmlString(String data) {

            try {

                // Create the Pull Parser
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                XmlPullParser xpp = factory.newPullParser();

                xpp.setInput(new StringReader(data));

                // Get the first Parser event and start iterating over the XML document
                int eventType = xpp.getEventType();

                while (eventType != XmlPullParser.END_DOCUMENT) {

                    if (eventType == XmlPullParser.START_TAG) {
                        startTag(xpp.getName());
                    } else if (eventType == XmlPullParser.END_TAG) {
                        endTag(xpp.getName());
                    } else if (eventType == XmlPullParser.TEXT) {
                        text(xpp.getText());
                    }
                    eventType = xpp.next();
                }
                return mResults;
            } catch (XmlPullParserException | IOException e) {
                e.printStackTrace();
            }
            return null;
        }
 
Example 15
Source File: DefaultXmlParser.java    From clevertap-android-sdk with MIT License 4 votes vote down vote up
static HashMap<String, String> getDefaultsFromXml(Context context, int resourceId) {
    HashMap<String,String> defaultsMap = new HashMap<>();

    try {
        Resources resources = context.getResources();
        if (resources == null) {
            Log.e("ProductConfig", "Could not find the resources of the current context while trying to set defaults from an XML.");
            return defaultsMap;
        }

        XmlResourceParser xmlParser = resources.getXml(resourceId);
        String curTag = null;
        String key = null;
        String value = null;

        for (int eventType = xmlParser.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xmlParser.next()) {
            if (eventType == XmlPullParser.START_TAG) {
                curTag = xmlParser.getName();
            } else if (eventType != XmlPullParser.END_TAG) {
                if (eventType == XmlPullParser.TEXT && curTag != null) {
                    byte tagType = -1;
                    switch (curTag) {
                        case XML_TAG_KEY:
                            tagType = XML_TAG_TYPE_KEY;
                            break;
                        case XML_TAG_VALUE:
                            tagType = XML_TAG_TYPE_VALUE;
                    }

                    switch (tagType) {
                        case XML_TAG_TYPE_KEY:
                            key = xmlParser.getText();
                            break;
                        case XML_TAG_TYPE_VALUE:
                            value = xmlParser.getText();
                            break;
                        default:
                            Log.w(LOG_TAG_PRODUCT_CONFIG, "Encountered an unexpected tag while parsing the defaults XML.");
                    }
                }
            } else {
                if (xmlParser.getName().equals(XML_TAG_ENTRY)) {
                    if (key != null && value != null) {
                        defaultsMap.put(key, value);
                    } else {
                        Log.w(LOG_TAG_PRODUCT_CONFIG, "An entry in the defaults XML has an invalid key and/or value tag.");
                    }

                    key = null;
                    value = null;
                }

                curTag = null;
            }
        }
    } catch (IOException | XmlPullParserException var11) {
        Log.e("ProductConfig", "Encountered an error while parsing the defaults XML file.", var11);
    }

    return defaultsMap;
}
 
Example 16
Source File: PreferenceParser.java    From SearchPreference with MIT License 4 votes vote down vote up
private ArrayList<PreferenceItem> parseFile(SearchConfiguration.SearchIndexItem item) {
    java.util.ArrayList<PreferenceItem> results = new ArrayList<>();
    XmlPullParser xpp = context.getResources().getXml(item.getResId());

    try {
        xpp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
        xpp.setFeature(XmlPullParser.FEATURE_REPORT_NAMESPACE_ATTRIBUTES, true);
        ArrayList<String> breadcrumbs = new ArrayList<>();
        ArrayList<String> keyBreadcrumbs = new ArrayList<>();
        if (!TextUtils.isEmpty(item.getBreadcrumb())) {
            breadcrumbs.add(item.getBreadcrumb());
        }
        while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
            if (xpp.getEventType() == XmlPullParser.START_TAG) {
                PreferenceItem result = parseSearchResult(xpp);
                result.resId = item.getResId();

                if (!BLACKLIST.contains(xpp.getName()) && result.hasData()) {
                    result.breadcrumbs = joinBreadcrumbs(breadcrumbs);
                    result.keyBreadcrumbs = cleanupKeyBreadcrumbs(keyBreadcrumbs);
                    if (!"true".equals(getAttribute(xpp, NS_SEARCH, "ignore"))) {
                        results.add(result);
                    }
                }
                if (CONTAINERS.contains(xpp.getName())) {
                    breadcrumbs.add(result.title == null ? "" : result.title);
                }
                if (xpp.getName().equals("PreferenceScreen")) {
                    keyBreadcrumbs.add(getAttribute(xpp, "key"));
                }
            } else if (xpp.getEventType() == XmlPullParser.END_TAG && CONTAINERS.contains(xpp.getName())) {
                breadcrumbs.remove(breadcrumbs.size() - 1);
                if (xpp.getName().equals("PreferenceScreen")) {
                    keyBreadcrumbs.remove(keyBreadcrumbs.size() - 1);
                }
            }

            xpp.next();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return results;
}
 
Example 17
Source File: DashManifestParser.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses an event object.
 *
 * @param xpp The current xml parser.
 * @param scratchOutputStream A {@link ByteArrayOutputStream} that's used when parsing the object.
 * @return The serialized byte array.
 * @throws XmlPullParserException If there is any error parsing this node.
 * @throws IOException If there is any error reading from the underlying input stream.
 */
protected byte[] parseEventObject(XmlPullParser xpp, ByteArrayOutputStream scratchOutputStream)
    throws XmlPullParserException, IOException {
  scratchOutputStream.reset();
  XmlSerializer xmlSerializer = Xml.newSerializer();
  xmlSerializer.setOutput(scratchOutputStream, null);
  // Start reading everything between <Event> and </Event>, and serialize them into an Xml
  // byte array.
  xpp.nextToken();
  while (!XmlPullParserUtil.isEndTag(xpp, "Event")) {
    switch (xpp.getEventType()) {
      case (XmlPullParser.START_DOCUMENT):
        xmlSerializer.startDocument(null, false);
        break;
      case (XmlPullParser.END_DOCUMENT):
        xmlSerializer.endDocument();
        break;
      case (XmlPullParser.START_TAG):
        xmlSerializer.startTag(xpp.getNamespace(), xpp.getName());
        for (int i = 0; i < xpp.getAttributeCount(); i++) {
          xmlSerializer.attribute(xpp.getAttributeNamespace(i), xpp.getAttributeName(i),
              xpp.getAttributeValue(i));
        }
        break;
      case (XmlPullParser.END_TAG):
        xmlSerializer.endTag(xpp.getNamespace(), xpp.getName());
        break;
      case (XmlPullParser.TEXT):
        xmlSerializer.text(xpp.getText());
        break;
      case (XmlPullParser.CDSECT):
        xmlSerializer.cdsect(xpp.getText());
        break;
      case (XmlPullParser.ENTITY_REF):
        xmlSerializer.entityRef(xpp.getText());
        break;
      case (XmlPullParser.IGNORABLE_WHITESPACE):
        xmlSerializer.ignorableWhitespace(xpp.getText());
        break;
      case (XmlPullParser.PROCESSING_INSTRUCTION):
        xmlSerializer.processingInstruction(xpp.getText());
        break;
      case (XmlPullParser.COMMENT):
        xmlSerializer.comment(xpp.getText());
        break;
      case (XmlPullParser.DOCDECL):
        xmlSerializer.docdecl(xpp.getText());
        break;
      default: // fall out
    }
    xpp.nextToken();
  }
  xmlSerializer.flush();
  return scratchOutputStream.toByteArray();
}
 
Example 18
Source File: MenuInflater.java    From android-apps with MIT License 4 votes vote down vote up
/**
 * Called internally to fill the given menu. If a sub menu is seen, it will
 * call this recursively.
 */
private void parseMenu(XmlPullParser parser, AttributeSet attrs, Menu menu)
        throws XmlPullParserException, IOException {
    MenuState menuState = new MenuState(menu);

    int eventType = parser.getEventType();
    String tagName;
    boolean lookingForEndOfUnknownTag = false;
    String unknownTagName = null;

    // This loop will skip to the menu start tag
    do {
        if (eventType == XmlPullParser.START_TAG) {
            tagName = parser.getName();
            if (tagName.equals(XML_MENU)) {
                // Go to next tag
                eventType = parser.next();
                break;
            }

            throw new RuntimeException("Expecting menu, got " + tagName);
        }
        eventType = parser.next();
    } while (eventType != XmlPullParser.END_DOCUMENT);

    boolean reachedEndOfMenu = false;
    while (!reachedEndOfMenu) {
        switch (eventType) {
            case XmlPullParser.START_TAG:
                if (lookingForEndOfUnknownTag) {
                    break;
                }

                tagName = parser.getName();
                if (tagName.equals(XML_GROUP)) {
                    menuState.readGroup(attrs);
                } else if (tagName.equals(XML_ITEM)) {
                    menuState.readItem(attrs);
                } else if (tagName.equals(XML_MENU)) {
                    // A menu start tag denotes a submenu for an item
                    SubMenu subMenu = menuState.addSubMenuItem();

                    // Parse the submenu into returned SubMenu
                    parseMenu(parser, attrs, subMenu);
                } else {
                    lookingForEndOfUnknownTag = true;
                    unknownTagName = tagName;
                }
                break;

            case XmlPullParser.END_TAG:
                tagName = parser.getName();
                if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) {
                    lookingForEndOfUnknownTag = false;
                    unknownTagName = null;
                } else if (tagName.equals(XML_GROUP)) {
                    menuState.resetGroup();
                } else if (tagName.equals(XML_ITEM)) {
                    // Add the item if it hasn't been added (if the item was
                    // a submenu, it would have been added already)
                    if (!menuState.hasAddedItem()) {
                        if (menuState.itemActionProvider != null &&
                                menuState.itemActionProvider.hasSubMenu()) {
                            menuState.addSubMenuItem();
                        } else {
                            menuState.addItem();
                        }
                    }
                } else if (tagName.equals(XML_MENU)) {
                    reachedEndOfMenu = true;
                }
                break;

            case XmlPullParser.END_DOCUMENT:
                throw new RuntimeException("Unexpected end of document");
        }

        eventType = parser.next();
    }
}
 
Example 19
Source File: JPGameGrabTask.java    From NintendoSwitchEShopHelper with GNU General Public License v3.0 4 votes vote down vote up
private void parseXMLWithPullAndAddToDb(String xmlData) {
    try {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        XmlPullParser xmlPullParser = factory.newPullParser();
        xmlPullParser.setInput(new StringReader(xmlData));
        int eventType = xmlPullParser.getEventType();

        JPGame jpGame = null;

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String nodeName = xmlPullParser.getName();
            switch (eventType) {
                case XmlPullParser.START_TAG: {
                    switch (nodeName) {
                        case "InitialCode":
                            jpGame = new JPGame();
                            jpGame.setInitialCode(parseGameCode(xmlPullParser.nextText()));
                            break;
                        case "TitleName":
                            jpGame.setTitleName(xmlPullParser.nextText());
                            break;
                        case "MakerName":
                            jpGame.setMakerName(xmlPullParser.nextText());
                            break;
                        case "MakerKana":
                            jpGame.setMakerKana(xmlPullParser.nextText());
                            break;
                        case "Price":
                            jpGame.setPrice(xmlPullParser.nextText());
                            break;
                        case "SalesDate":
                            jpGame.setSalesDate(xmlPullParser.nextText());
                            break;
                        case "SoftType":
                            jpGame.setSoftType(xmlPullParser.nextText());
                            break;
                        case "PlatformID":
                            jpGame.setPlatformID(xmlPullParser.nextText());
                            break;
                        case "DlIconFlg":
                            jpGame.setDlIconFlg(xmlPullParser.nextText());
                            break;
                        case "LinkURL":
                            // Parse the LinkURL to complete url
                            jpGame.setLinkURL("https://ec.nintendo.com/JP/ja" + xmlPullParser.nextText());
                            break;
                        case "ScreenshotImgFlg":
                            jpGame.setScreenshotImgFlg(xmlPullParser.nextText());
                            break;
                        case "ScreenshotImgURL":
                            jpGame.setScreenshotImgURL(xmlPullParser.nextText());
                            jpGame.setNsUid(parseNsUid(jpGame.getLinkURL()));
                            addJPGame(jpGame);
                            break;
                    }
                    break;
                }
                case XmlPullParser.END_TAG: {
                    break;
                }
                default:
                    break;
            }
            eventType = xmlPullParser.next();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 20
Source File: LocaleController.java    From Yahala-Messenger with MIT License 4 votes vote down vote up
private HashMap<String, String> getLocaleFileStrings(File file) {
    try {
        HashMap<String, String> stringMap = new HashMap<String, String>();
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(new FileInputStream(file), "UTF-8");
        int eventType = parser.getEventType();
        String name = null;
        String value = null;
        String attrName = null;
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                name = parser.getName();
                int c = parser.getAttributeCount();
                if (c > 0) {
                    attrName = parser.getAttributeValue(0);
                }
            } else if (eventType == XmlPullParser.TEXT) {
                if (attrName != null) {
                    value = parser.getText();
                    if (value != null) {
                        value = value.trim();
                        value = value.replace("\\n", "\n");
                        value = value.replace("\\", "");
                    }
                }
            } else if (eventType == XmlPullParser.END_TAG) {
                value = null;
                attrName = null;
                name = null;
            }
            if (name != null && name.equals("string") && value != null && attrName != null && value.length() != 0 && attrName.length() != 0) {
                stringMap.put(attrName, value);
                name = null;
                value = null;
                attrName = null;
            }
            eventType = parser.next();
        }
        return stringMap;
    } catch (Exception e) {
        FileLog.e("yahala", e);
    }
    return null;
}