Java Code Examples for android.content.res.XmlResourceParser#getAttributeValue()

The following examples show how to use android.content.res.XmlResourceParser#getAttributeValue() . 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: XmlConfigSource.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private CertificatesEntryRef parseCertificatesEntry(XmlResourceParser parser,
        boolean defaultOverridePins)
        throws IOException, XmlPullParserException, ParserException {
    boolean overridePins =
            parser.getAttributeBooleanValue(null, "overridePins", defaultOverridePins);
    int sourceId = parser.getAttributeResourceValue(null, "src", -1);
    String sourceString = parser.getAttributeValue(null, "src");
    CertificateSource source = null;
    if (sourceString == null) {
        throw new ParserException(parser, "certificates element missing src attribute");
    }
    if (sourceId != -1) {
        // TODO: Cache ResourceCertificateSources by sourceId
        source = new ResourceCertificateSource(sourceId, mContext);
    } else if ("system".equals(sourceString)) {
        source = SystemCertificateSource.getInstance();
    } else if ("user".equals(sourceString)) {
        source = UserCertificateSource.getInstance();
    } else {
        throw new ParserException(parser, "Unknown certificates src. "
                + "Should be one of system|user|@resourceVal");
    }
    XmlUtils.skipCurrentTag(parser);
    return new CertificatesEntryRef(source, overridePins);
}
 
Example 2
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 3
Source File: RecognitionServiceManager.java    From speechutils with Apache License 2.0 5 votes vote down vote up
public static String getSettingsActivity(Context context, ServiceInfo si)
        throws XmlPullParserException, IOException {
    PackageManager pm = context.getPackageManager();
    XmlResourceParser parser = null;
    try {
        parser = si.loadXmlMetaData(pm, RecognitionService.SERVICE_META_DATA);
        if (parser == null) {
            throw new XmlPullParserException("No " + RecognitionService.SERVICE_META_DATA + " meta-data");
        }

        int type;
        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
                && type != XmlPullParser.START_TAG) {
        }

        String nodeName = parser.getName();
        if (!"recognition-service".equals(nodeName)) {
            throw new XmlPullParserException(
                    "Meta-data does not start with recognition-service tag");
        }

        return parser.getAttributeValue("http://schemas.android.com/apk/res/android",
                "settingsActivity");
    } finally {
        if (parser != null) parser.close();
    }
}
 
Example 4
Source File: Contract.java    From LecteurOPUS with GNU General Public License v3.0 5 votes vote down vote up
public void setLogoFromXml(Context ctx){
    String node = "";
    String logo = "";
    m_operatorName = "";
    XmlResourceParser operatorXml = ctx.getResources().getXml(R.xml.operators);
    try {
        int event = operatorXml.getEventType();
        outerloop:
        while (event != XmlPullParser.END_DOCUMENT){
            switch (event) {
                case XmlPullParser.START_TAG:
                    node = operatorXml.getName();
                    if(node.equals("operator")) {
                        if (operatorXml.getAttributeValue(null, "id").equals("" + m_operatorId)) {
                            logo = operatorXml.getAttributeValue(null, "logo");
                            m_operatorName = operatorXml.getAttributeValue(null, "name");
                            break outerloop;
                        }
                    }
                    break;
            }
            event = operatorXml.next();
        }
    } catch (Exception e) {
        Log.e("CardActivity", "Error parsing stations XML file: " + e.getMessage());
    }

    m_logoId = 0;
    if (!logo.equals("")){
        m_logoId = ctx.getResources().getIdentifier(logo, "drawable", ctx.getPackageName());
    }
}
 
Example 5
Source File: XmlConfigSource.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
private PinSet parsePinSet(XmlResourceParser parser)
        throws IOException, XmlPullParserException, ParserException {
    String expirationDate = parser.getAttributeValue(null, "expiration");
    long expirationTimestampMilis = Long.MAX_VALUE;
    if (expirationDate != null) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.setLenient(false);
            Date date = sdf.parse(expirationDate);
            if (date == null) {
                throw new ParserException(parser, "Invalid expiration date in pin-set");
            }
            expirationTimestampMilis = date.getTime();
        } catch (ParseException e) {
            throw new ParserException(parser, "Invalid expiration date in pin-set", e);
        }
    }

    int outerDepth = parser.getDepth();
    Set<Pin> pins = new HashSet<>();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        String tagName = parser.getName();
        if (tagName.equals("pin")) {
            pins.add(parsePin(parser));
        } else {
            XmlUtils.skipCurrentTag(parser);
        }
    }
    return new PinSet(pins, expirationTimestampMilis);
}
 
Example 6
Source File: Keyboard.java    From WirelessHid with Apache License 2.0 5 votes vote down vote up
private String getStringAttributeValue(XmlResourceParser xmlParser, String attributeName,
        String defaultValue) {
    String value = xmlParser.getAttributeValue(null, attributeName);
    if (value != null)
        return value;
    return defaultValue;
}
 
Example 7
Source File: PluginManifestParser.java    From Android-Plugin-Framework with MIT License 5 votes vote down vote up
private static String addIntentFilter(HashMap<String, ArrayList<PluginIntentFilter>> map, String packageName, String namespace,
                                         XmlResourceParser parser, String endTagName) throws XmlPullParserException, IOException {
	int eventType = parser.getEventType();
	String activityName = parser.getAttributeValue(namespace, "name");
	activityName = getName(activityName, packageName);

	ArrayList<PluginIntentFilter> filters = map.get(activityName);
	if (filters == null) {
		filters = new ArrayList<PluginIntentFilter>();
           map.put(activityName, filters);
	}
	
	PluginIntentFilter intentFilter = new PluginIntentFilter();
	do {
		switch (eventType) {
			case XmlPullParser.START_TAG: {
				String tag = parser.getName();
				if ("intent-filter".equals(tag)) {
					intentFilter = new PluginIntentFilter();
					filters.add(intentFilter);
				} else {
					intentFilter.readFromXml(tag, namespace, parser);
				}
			}
		}
		eventType = parser.next();
	} while (!endTagName.equals(parser.getName()));//再次到达,表示一个标签结束了

       return activityName;
}
 
Example 8
Source File: LiteIconActivityV2.java    From NanoIconPackLite with Apache License 2.0 5 votes vote down vote up
private List<Cate> getIcons() {
    List<Cate> dataList = new ArrayList<>();
    Cate defCate = new Cate(null);
    XmlResourceParser parser = getResources().getXml(R.xml.drawable);
    try {
        int event = parser.getEventType();
        while (event != XmlPullParser.END_DOCUMENT) {
            if (event == XmlPullParser.START_TAG) {
                switch (parser.getName()) {
                    case "category":
                        dataList.add(new Cate(parser.getAttributeValue(null, "title")));
                        break;
                    case "item":
                        String iconName = parser.getAttributeValue(null, "drawable");
                        if (dataList.isEmpty()) {
                            defCate.pushIcon(iconName);
                        } else {
                            dataList.get(dataList.size() - 1).pushIcon(iconName);
                        }
                        break;
                }
            }
            event = parser.next();
        }
        if (!defCate.isEmpty()) {
            dataList.add(defCate);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dataList;
}
 
Example 9
Source File: ChangeLogDialog.java    From iBeebo with GNU General Public License v3.0 5 votes vote down vote up
private String ParseReleaseTag(XmlResourceParser aXml) throws XmlPullParserException, IOException {
    String _Result = "<h1>版本: " + aXml.getAttributeValue(null, "version") + "</h1><ul>";
    int eventType = aXml.getEventType();
    while ((eventType != XmlPullParser.END_TAG) || (aXml.getName().equals("change"))) {
        if ((eventType == XmlPullParser.START_TAG) && (aXml.getName().equals("change"))) {
            eventType = aXml.next();
            _Result = _Result + "<li>" + aXml.getText() + "</li>";
        }
        eventType = aXml.next();
    }
    _Result = _Result + "</ul>";
    return _Result;
}
 
Example 10
Source File: XmlKeyboardLoader.java    From AndroidTVWidget with Apache License 2.0 5 votes vote down vote up
private boolean getBoolean(XmlResourceParser xrp, String name, boolean defValue) {
	String s = xrp.getAttributeValue(null, name);
	if (null == s)
		return defValue;
	try {
		boolean ret = Boolean.parseBoolean(s);
		return ret;
	} catch (NumberFormatException e) {
		return defValue;
	}
}
 
Example 11
Source File: SettingChangeLogDialog.java    From iBeebo with GNU General Public License v3.0 5 votes vote down vote up
private String ParseReleaseTag(XmlResourceParser aXml) throws XmlPullParserException, IOException {
    String _Result = "<h1>Release: " + aXml.getAttributeValue(null, "version") + "</h1><ul>";
    int eventType = aXml.getEventType();
    while ((eventType != XmlPullParser.END_TAG) || (aXml.getName().equals("change"))) {
        if ((eventType == XmlPullParser.START_TAG) && (aXml.getName().equals("change"))) {
            eventType = aXml.next();
            _Result = _Result + "<li>" + aXml.getText() + "</li>";
        }
        eventType = aXml.next();
    }
    _Result = _Result + "</ul>";
    return _Result;
}
 
Example 12
Source File: DateSpinner.java    From ReminderDatePicker with Apache License 2.0 4 votes vote down vote up
@Override
protected @Nullable TwinTextItem parseItemFromXmlTag(@NonNull XmlResourceParser parser) {
    if(!parser.getName().equals(XML_TAG_DATEITEM)) {
        Log.d("DateSpinner", "Unknown xml tag name: " + parser.getName());
        return null;
    }

    // parse the DateItem, possible values are
    String text = null;
    @StringRes int textResource = NO_ID, id = NO_ID;
    Calendar date = Calendar.getInstance();
    for(int i=parser.getAttributeCount()-1; i>=0; i--) {
        String attrName = parser.getAttributeName(i);
        switch (attrName) {
            case XML_ATTR_ID:
                id = parser.getIdAttributeResourceValue(NO_ID);
                break;
            case XML_ATTR_TEXT:
                text = parser.getAttributeValue(i);
                // try to get a resource value, the string is retrieved below
                if(text != null && text.startsWith("@"))
                    textResource = parser.getAttributeResourceValue(i, NO_ID);
                break;

            case XML_ATTR_ABSDAYOFYEAR:
                final int absDayOfYear = parser.getAttributeIntValue(i, -1);
                if(absDayOfYear > 0)
                    date.set(Calendar.DAY_OF_YEAR, absDayOfYear);
                break;
            case XML_ATTR_ABSDAYOFMONTH:
                final int absDayOfMonth = parser.getAttributeIntValue(i, -1);
                if(absDayOfMonth > 0)
                    date.set(Calendar.DAY_OF_MONTH, absDayOfMonth);
                break;
            case XML_ATTR_ABSMONTH:
                final int absMonth = parser.getAttributeIntValue(i, -1);
                if(absMonth >= 0)
                    date.set(Calendar.MONTH, absMonth);
                break;
            case XML_ATTR_ABSYEAR:
                final int absYear = parser.getAttributeIntValue(i, -1);
                if(absYear >= 0)
                    date.set(Calendar.YEAR, absYear);
                break;

            case XML_ATTR_RELDAY:
                final int relDay = parser.getAttributeIntValue(i, 0);
                date.add(Calendar.DAY_OF_YEAR, relDay);
                break;
            case XML_ATTR_RELMONTH:
                final int relMonth = parser.getAttributeIntValue(i, 0);
                date.add(Calendar.MONTH, relMonth);
                break;
            case XML_ATTR_RELYEAR:
                final int relYear = parser.getAttributeIntValue(i, 0);
                date.add(Calendar.YEAR, relYear);
                break;
            default:
                Log.d("DateSpinner", "Skipping unknown attribute tag parsing xml resource: "
                        + attrName + ", maybe a typo?");
        }
    }// end for attr

    // now construct the date item from the attributes

    // check if we got a textResource earlier and parse that string together with the weekday
    if(textResource != NO_ID)
        text = getWeekDay(date.get(Calendar.DAY_OF_WEEK), textResource);

    // when no text is given, format the date to have at least something to show
    if(text == null || text.equals(""))
        text = formatDate(date);

    return new DateItem(text, date, id);
}
 
Example 13
Source File: FileProvider.java    From MiBandDecompiled with Apache License 2.0 4 votes vote down vote up
private static d b(Context context, String s)
{
    e e1 = new e(s);
    XmlResourceParser xmlresourceparser = context.getPackageManager().resolveContentProvider(s, 128).loadXmlMetaData(context.getPackageManager(), "android.support.FILE_PROVIDER_PATHS");
    if (xmlresourceparser == null)
    {
        throw new IllegalArgumentException("Missing android.support.FILE_PROVIDER_PATHS meta-data");
    }
    do
    {
        int l = xmlresourceparser.next();
        if (l != 1)
        {
            if (l == 2)
            {
                String s1 = xmlresourceparser.getName();
                String s2 = xmlresourceparser.getAttributeValue(null, "name");
                String s3 = xmlresourceparser.getAttributeValue(null, "path");
                File file;
                if ("root-path".equals(s1))
                {
                    file = a(i, new String[] {
                        s3
                    });
                } else
                if ("files-path".equals(s1))
                {
                    file = a(context.getFilesDir(), new String[] {
                        s3
                    });
                } else
                if ("cache-path".equals(s1))
                {
                    file = a(context.getCacheDir(), new String[] {
                        s3
                    });
                } else
                if ("external-path".equals(s1))
                {
                    file = a(Environment.getExternalStorageDirectory(), new String[] {
                        s3
                    });
                } else
                {
                    file = null;
                }
                if (file != null)
                {
                    e1.a(s2, file);
                }
            }
        } else
        {
            return e1;
        }
    } while (true);
}
 
Example 14
Source File: AndroidManifestParser.java    From Phantom with Apache License 2.0 4 votes vote down vote up
private static String getNameAttrValue(XmlResourceParser parser) {
    return parser.getAttributeValue(NAMESPACE_ANDROID, "name");
}
 
Example 15
Source File: FileProvider.java    From guideshow with MIT License 4 votes vote down vote up
/**
 * Parse and return {@link PathStrategy} for given authority as defined in
 * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code &lt;meta-data>}.
 *
 * @see #getPathStrategy(Context, String)
 */
private static PathStrategy parsePathStrategy(Context context, String authority)
        throws IOException, XmlPullParserException {
    final SimplePathStrategy strat = new SimplePathStrategy(authority);

    final ProviderInfo info = context.getPackageManager()
            .resolveContentProvider(authority, PackageManager.GET_META_DATA);
    final XmlResourceParser in = info.loadXmlMetaData(
            context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
    if (in == null) {
        throw new IllegalArgumentException(
                "Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
    }

    int type;
    while ((type = in.next()) != END_DOCUMENT) {
        if (type == START_TAG) {
            final String tag = in.getName();

            final String name = in.getAttributeValue(null, ATTR_NAME);
            String path = in.getAttributeValue(null, ATTR_PATH);

            File target = null;
            if (TAG_ROOT_PATH.equals(tag)) {
                target = buildPath(DEVICE_ROOT, path);
            } else if (TAG_FILES_PATH.equals(tag)) {
                target = buildPath(context.getFilesDir(), path);
            } else if (TAG_CACHE_PATH.equals(tag)) {
                target = buildPath(context.getCacheDir(), path);
            } else if (TAG_EXTERNAL.equals(tag)) {
                target = buildPath(Environment.getExternalStorageDirectory(), path);
            }

            if (target != null) {
                strat.addRoot(name, target);
            }
        }
    }

    return strat;
}
 
Example 16
Source File: ParseLicenseXml.java    From LicenseView with Apache License 2.0 4 votes vote down vote up
public static List<License> Parse(XmlResourceParser parser)
		throws XmlPullParserException, IOException {
	List<License> licenses = new ArrayList<License>();
	int event = parser.getEventType();

	String name = null;
	String type = null;
	String license = null;

	while (event != XmlResourceParser.END_DOCUMENT) {
		if (event == XmlResourceParser.START_TAG) {
			if (!parser.getName().equals(TAG_ROOT)
					&& !parser.getName().equals(TAG_CHILD))
				throw new XmlPullParserException(
						"Error in xml: tag isn't '" + TAG_ROOT + "' or '"
								+ TAG_CHILD + "' at line:"
								+ parser.getLineNumber());
			name = parser.getAttributeValue(null, ATTR_NAME);
			type = parser.getAttributeValue(null, ATTR_TYPE);
		} else if (event == XmlResourceParser.TEXT) {
			license = parser.getText();
		} else if (event == XmlResourceParser.END_TAG) {
			if (name != null && type != null && license != null
					&& !parser.getName().equals(TAG_ROOT)) {
				if (type.equals(VALUE_FILE)) {
					licenses.add(new License(name, License.TYPE_FILE,
							license));
					System.out.println(name);
				} else if (type.equals(VALUE_LIBRARY)) {
					licenses.add(new License(name, License.TYPE_LIBRARY,
							license));
					System.out.println(name);
				} else {
					throw new XmlPullParserException(
							"Error in xml: 'type' isn't valid at line:"
									+ parser.getLineNumber());
				}
			} else if (name == null) {
				throw new XmlPullParserException(
						"Error in xml: doesn't contain a 'name' at line:"
								+ parser.getLineNumber());
			} else if (type == null) {
				throw new XmlPullParserException(
						"Error in xml: doesn't contain a 'type' at line:"
								+ parser.getLineNumber());
			} else if (license == null){
				throw new XmlPullParserException(
						"Error in xml: doesn't contain a 'license text' at line:"
								+ parser.getLineNumber());
			}
		}
		event = parser.next();
	}
	parser.close();
	return licenses;
}
 
Example 17
Source File: AndroidFont.java    From CrossMobile with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("UseSpecificCatch")
private static Map<String, Map<String, FontInfo>> fonts() {
    if (font_map != null)
        return font_map;

    font_map = new LinkedHashMap<>();

    Map<String, FontInfo> family = new LinkedHashMap<>();
    family.put("Sans Serif Regular", new FontInfo(false, false, Typeface.SANS_SERIF));
    family.put("Sans Serif Italic", new FontInfo(false, true, Typeface.SANS_SERIF));
    family.put("Sans Serif Bold", new FontInfo(true, false, Typeface.SANS_SERIF));
    family.put("Sans Serif Bold Italic", new FontInfo(true, true, Typeface.SANS_SERIF));
    font_map.put("Sans Serif", family);

    family = new LinkedHashMap<>();
    family.put("Serif", new FontInfo(false, false, Typeface.SERIF));
    font_map.put("Serif", family);

    family = new LinkedHashMap<>();
    family.put("Monospace", new FontInfo(false, false, Typeface.MONOSPACE));
    font_map.put("Monospace", family);

    XmlResourceParser parser = MainActivity.current.getResources().getXml(AndroidFileBridge.getResourceID("xml", "fontlist"));
    try {
        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (parser.getName().equals("font")) {
                        String file = parser.getAttributeValue(null, "file");
                        String familyname = parser.getAttributeValue(null, "family");
                        String name = parser.getAttributeValue(null, "name");
                        boolean bold = parser.getAttributeBooleanValue(null, "bold", false);
                        boolean italic = parser.getAttributeBooleanValue(null, "italic", false);
                        family = font_map.get(familyname);
                        if (family == null) {
                            family = new LinkedHashMap<>();
                            font_map.put(familyname, family);
                        }
                        family.put(name, new FontInfo(bold, italic, file));
                    }
                    break;
                default:
                    break;
            }
            eventType = parser.next();
        }
        parser.close();
    } catch (Exception e) {
    }
    return font_map;
}
 
Example 18
Source File: ResourceUtils.java    From mimi-reader with Apache License 2.0 4 votes vote down vote up
public static Map<String,String> getHashMapResource(Context c, int hashMapResId) {
    Map<String,String> map = null;
    XmlResourceParser parser = c.getResources().getXml(hashMapResId);

    String key = null, value = null;

    try {
        int eventType = parser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_DOCUMENT) {
                Log.d("utils","Start document");
            } else if (eventType == XmlPullParser.START_TAG) {
                if (parser.getName().equals("map")) {
                    boolean isLinked = parser.getAttributeBooleanValue(null, "linked", false);

                    map = isLinked ? new LinkedHashMap<String, String>() : new HashMap<String, String>();
                } else if (parser.getName().equals("entry")) {
                    key = parser.getAttributeValue(null, "key");

                    if (null == key) {
                        parser.close();
                        return null;
                    }
                }
            } else if (eventType == XmlPullParser.END_TAG) {
                if (parser.getName().equals("entry")) {
                    map.put(key, value);
                    key = null;
                    value = null;
                }
            } else if (eventType == XmlPullParser.TEXT) {
                if (null != key) {
                    value = parser.getText();
                }
            }
            eventType = parser.next();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return map;
}
 
Example 19
Source File: FileProvider.java    From adt-leanback-support with Apache License 2.0 4 votes vote down vote up
/**
 * Parse and return {@link PathStrategy} for given authority as defined in
 * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code &lt;meta-data>}.
 *
 * @see #getPathStrategy(Context, String)
 */
private static PathStrategy parsePathStrategy(Context context, String authority)
        throws IOException, XmlPullParserException {
    final SimplePathStrategy strat = new SimplePathStrategy(authority);

    final ProviderInfo info = context.getPackageManager()
            .resolveContentProvider(authority, PackageManager.GET_META_DATA);
    final XmlResourceParser in = info.loadXmlMetaData(
            context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
    if (in == null) {
        throw new IllegalArgumentException(
                "Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
    }

    int type;
    while ((type = in.next()) != END_DOCUMENT) {
        if (type == START_TAG) {
            final String tag = in.getName();

            final String name = in.getAttributeValue(null, ATTR_NAME);
            String path = in.getAttributeValue(null, ATTR_PATH);

            File target = null;
            if (TAG_ROOT_PATH.equals(tag)) {
                target = buildPath(DEVICE_ROOT, path);
            } else if (TAG_FILES_PATH.equals(tag)) {
                target = buildPath(context.getFilesDir(), path);
            } else if (TAG_CACHE_PATH.equals(tag)) {
                target = buildPath(context.getCacheDir(), path);
            } else if (TAG_EXTERNAL.equals(tag)) {
                target = buildPath(Environment.getExternalStorageDirectory(), path);
            }

            if (target != null) {
                strat.addRoot(name, target);
            }
        }
    }

    return strat;
}
 
Example 20
Source File: ApduParser.java    From nfcspy with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
static Apdu7816 readTag(Class<? extends Apdu7816> clazz,
		XmlResourceParser xml) throws Exception {
	if (xml.getEventType() != START_TAG)
		return null;

	final String thisTag = xml.getName();
	final String testTag = (String) clazz.getDeclaredField("TAG").get(null);
	if (!thisTag.equalsIgnoreCase(testTag))
		return null;

	final String apduName = xml.getAttributeValue(null, "name");
	final String apduVal = xml.getAttributeValue(null, "val");
	final ArrayList<Apdu7816> list = new ArrayList<Apdu7816>();

	final Object child = clazz.getDeclaredField("SUB").get(null);
	while (true) {
		int event = xml.next();
		if (event == END_DOCUMENT)
			break;

		if (event == END_TAG && thisTag.equalsIgnoreCase(xml.getName()))
			break;

		if (child != null) {
			Apdu7816 apdu = readTag((Class<? extends Apdu7816>) child, xml);
			if (apdu != null)
				list.add(apdu);
		}
	}

	final Apdu7816[] sub;
	if (list.isEmpty())
		sub = null;
	else
		sub = list.toArray(new Apdu7816[list.size()]);

	final Apdu7816 ret = clazz.newInstance();

	ret.init(parseValue(apduVal), apduName, sub);

	return ret;
}