下面列出了android.content.res.XmlResourceParser#next() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void readRelease(XmlResourceParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, null, TAG_RELEASE);
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals(TAG_CHANGE)) {
parser.require(XmlPullParser.START_TAG, null, TAG_CHANGE);
String variant = parser.getAttributeValue(null, ATTRIBUTE_VARIANT);
ChangeListItem changeItem = new ChangeListItem();
changeItem.change = readText(parser);
if (BuildConfig.FULL_VERSION || !"full".equals(variant))
mChangelog.add(changeItem);
parser.require(XmlPullParser.END_TAG, null, TAG_CHANGE);
} else {
skip(parser);
}
}
parser.require(XmlPullParser.END_TAG, null, TAG_RELEASE);
}
private Domain parseDomain(XmlResourceParser parser, Set<String> seenDomains)
throws IOException, XmlPullParserException, ParserException {
boolean includeSubdomains =
parser.getAttributeBooleanValue(null, "includeSubdomains", false);
if (parser.next() != XmlPullParser.TEXT) {
throw new ParserException(parser, "Domain name missing");
}
String domain = parser.getText().trim().toLowerCase(Locale.US);
if (parser.next() != XmlPullParser.END_TAG) {
throw new ParserException(parser, "domain contains additional elements");
}
// Domains are matched using a most specific match, so don't allow duplicates.
// includeSubdomains isn't relevant here, both android.com + subdomains and android.com
// match for android.com equally. Do not allow any duplicates period.
if (!seenDomains.add(domain)) {
throw new ParserException(parser, domain + " has already been specified");
}
return new Domain(domain, includeSubdomains);
}
@NonNull
public static Map<String, String> getFilterMap(XmlResourceParser parser)
throws XmlPullParserException, IOException {
Map<String, String> map = new HashMap<>();
for (int type = parser.getEventType(); type != XmlPullParser.END_DOCUMENT; type = parser.next()) {
if (type == XmlPullParser.START_TAG && Constants.FILTER_TAG_ITEM.equals(parser.getName())) {
map.put(
parser.getAttributeValue(null, Constants.FILTER_TAG_NAME),
parser.getAttributeValue(null, Constants.FILTER_TAG_VALUE)
);
}
}
return map;
}
private ArrayList<FrameVO> parseXML(XmlResourceParser parser) {
ArrayList<FrameVO> frames = new ArrayList<>();
try {
parser.next();
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("TextureAtlas")) {
} else if (parser.getName().equals("SubTexture")) {
frames.add(new FrameVO(parser));
}
}
eventType = parser.next();
}
} catch (XmlPullParserException | IOException e) {
e.printStackTrace();
}
return frames;
}
private ZenModeConfig readDefaultConfig(Resources resources) {
XmlResourceParser parser = null;
try {
parser = resources.getXml(R.xml.default_zen_mode_config);
while (parser.next() != XmlPullParser.END_DOCUMENT) {
final ZenModeConfig config = ZenModeConfig.readXml(parser);
if (config != null) return config;
}
} catch (Exception e) {
Log.w(TAG, "Error reading default zen mode config from resource", e);
} finally {
IoUtils.closeQuietly(parser);
}
return new ZenModeConfig();
}
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;
}
private static void skipCurrentTag(XmlResourceParser parser)
throws XmlPullParserException, IOException {
int outerDepth = parser.getDepth();
int type;
while ((type=parser.next()) != XmlResourceParser.END_DOCUMENT
&& (type != XmlResourceParser.END_TAG
|| parser.getDepth() > outerDepth)) {
}
}
private void parsePreferences(@NonNull final Context context, @NonNull final XmlResourceParser parser, @NonNull final WearPreferenceScreen screen)
throws XmlPullParserException, IOException {
if(parser.getEventType() == XmlResourceParser.START_TAG) {
parser.next();
while(parser.getEventType() != XmlResourceParser.END_TAG) {
parseItem(context, parser, screen);
parser.next();
}
}
}
private Pin parsePin(XmlResourceParser parser)
throws IOException, XmlPullParserException, ParserException {
String digestAlgorithm = parser.getAttributeValue(null, "digest");
if (!Pin.isSupportedDigestAlgorithm(digestAlgorithm)) {
throw new ParserException(parser, "Unsupported pin digest algorithm: "
+ digestAlgorithm);
}
if (parser.next() != XmlPullParser.TEXT) {
throw new ParserException(parser, "Missing pin digest");
}
String digest = parser.getText().trim();
byte[] decodedDigest = null;
try {
decodedDigest = Base64.decode(digest, 0);
} catch (IllegalArgumentException e) {
throw new ParserException(parser, "Invalid pin digest", e);
}
int expectedLength = Pin.getDigestLength(digestAlgorithm);
if (decodedDigest.length != expectedLength) {
throw new ParserException(parser, "digest length " + decodedDigest.length
+ " does not match expected length for " + digestAlgorithm + " of "
+ expectedLength);
}
if (parser.next() != XmlPullParser.END_TAG) {
throw new ParserException(parser, "pin contains additional elements");
}
return new Pin(digestAlgorithm, decodedDigest);
}
/**
* 解析Manifest节点
*/
private void parseManifest(XmlResourceParser parser) throws IOException, XmlPullParserException {
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG
&& type != XmlPullParser.END_DOCUMENT) {
// go on to find START_TAG
}
if (type != XmlPullParser.START_TAG) {
throw new XmlPullParserException("No start tag found");
}
if (!parser.getName().equals("manifest")) {
throw new XmlPullParserException("No <manifest> tag");
}
pkg = parser.getAttributeValue(null, "package");
Log.i(TAG, "parsed packageName=" + pkg);
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;
}
String tagName = parser.getName();
if (tagName.equals("application")) {
// found Application Tag
parseApplication(parser);
}
}
}
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;
}
@NonNull
public static List<Icon> getIconsList(@NonNull Context context) throws Exception {
XmlResourceParser parser = context.getResources().getXml(R.xml.drawable);
int eventType = parser.getEventType();
String sectionTitle = "";
List<Icon> icons = new ArrayList<>();
List<Icon> sections = new ArrayList<>();
int count = 0;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("category")) {
String title = parser.getAttributeValue(null, "title");
if (!sectionTitle.equals(title)) {
if (sectionTitle.length() > 0) {
count += icons.size();
sections.add(new Icon(sectionTitle, icons));
}
}
sectionTitle = title;
icons = new ArrayList<>();
} else if (parser.getName().equals("item")) {
String name = parser.getAttributeValue(null, "drawable");
String customName = parser.getAttributeValue(null, "name");
int id = getResourceId(context, name);
if (id > 0) {
icons.add(new Icon(name, customName, id));
}
}
}
eventType = parser.next();
}
count += icons.size();
CandyBarMainActivity.sIconsCount = count;
if (!CandyBarApplication.getConfiguration().isAutomaticIconsCountEnabled() &&
CandyBarApplication.getConfiguration().getCustomIconsCount() == 0) {
CandyBarApplication.getConfiguration().setCustomIconsCount(count);
}
sections.add(new Icon(sectionTitle, icons));
parser.close();
return sections;
}
private LinearLayout parseKeyLayout(Context context, XmlResourceParser xmlParser)
throws XmlPullParserException, IOException {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setLayoutParams(new LayoutParams(
xmlParser.getAttributeIntValue(null, "width", LayoutParams.MATCH_PARENT),
xmlParser.getAttributeIntValue(null, "height", 0),
xmlParser.getAttributeFloatValue(null, "weight", 1.0f)));
linearLayout.setOrientation(xmlParser.getAttributeIntValue(null, "orientation",
LinearLayout.HORIZONTAL));
String tag;
do {
xmlParser.next();
tag = xmlParser.getName();
if (xmlParser.getEventType() == XmlResourceParser.START_TAG) {
if (tag.equals(XML_TAG_LAYOUT)) {
linearLayout.addView(parseKeyLayout(context, xmlParser));
} else if (tag.equals(XML_TAG_KEY)) {
Key.KeyAttributes attrs = new Key.KeyAttributes();
attrs.keyFunction = getStringAttributeValue(xmlParser, "keyFunc", "");
attrs.mainLabel = getStringAttributeValue(xmlParser, "keyLabel", "");
attrs.shiftLabel = getStringAttributeValue(xmlParser, "shiftLabel", "");
attrs.keyCode = xmlParser.getAttributeIntValue(null, "keyCode", 0);
Key key = new Key(context, attrs);
key.setLayoutParams(new LayoutParams(
xmlParser.getAttributeIntValue(null, "width", 0),
xmlParser.getAttributeIntValue(null, "height",
LayoutParams.MATCH_PARENT),
xmlParser.getAttributeFloatValue(null, "weight", 1)));
key.setVisibility(xmlParser.getAttributeBooleanValue(null, "visible", true) ?
VISIBLE : INVISIBLE);
key.setKeyListener(this);
if (attrs.shiftLabel != null & attrs.shiftLabel.length() > 0) {
mKeysWithShiftLabel.add(key);
}
linearLayout.addView(key);
}
}
} while (xmlParser.getEventType() != XmlResourceParser.END_TAG
|| !tag.equals(XML_TAG_LAYOUT));
return linearLayout;
}
private void loadKeyboard(Context context, XmlResourceParser parser) {
boolean inKey = false;
boolean inRow = false;
boolean leftMostKey = false;
int row = 0;
int x = 0;
int y = 0;
Key key = null;
Row currentRow = null;
Resources res = context.getResources();
boolean skipRow = false;
try {
int event;
while ((event = parser.next()) != XmlResourceParser.END_DOCUMENT) {
if (event == XmlResourceParser.START_TAG) {
String tag = parser.getName();
if (TAG_ROW.equals(tag)) {
inRow = true;
x = 0;
currentRow = createRowFromXml(res, parser);
rows.add(currentRow);
skipRow = currentRow.mode != 0 && currentRow.mode != mKeyboardMode;
if (skipRow) {
skipToEndOfRow(parser);
inRow = false;
}
} else if (TAG_KEY.equals(tag)) {
inKey = true;
key = createKeyFromXml(res, currentRow, x, y, parser);
mKeys.add(key);
if (key.codes[0] == KEYCODE_SHIFT) {
// Find available shift key slot and put this shift key in it
for (int i = 0; i < mShiftKeys.length; i++) {
if (mShiftKeys[i] == null) {
mShiftKeys[i] = key;
mShiftKeyIndices[i] = mKeys.size()-1;
break;
}
}
mModifierKeys.add(key);
} else if (key.codes[0] == KEYCODE_ALT) {
mModifierKeys.add(key);
}
currentRow.mKeys.add(key);
} else if (TAG_KEYBOARD.equals(tag)) {
parseKeyboardAttributes(res, parser);
}
} else if (event == XmlResourceParser.END_TAG) {
if (inKey) {
inKey = false;
x += key.gap + key.width;
if (x > mTotalWidth) {
mTotalWidth = x;
}
} else if (inRow) {
inRow = false;
y += currentRow.verticalGap;
y += currentRow.defaultHeight;
row++;
} else {
// TODO: error or extend?
}
}
}
} catch (Exception e) {
Log.e(TAG, "Parse error:" + e);
e.printStackTrace();
}
mTotalHeight = y - mDefaultVerticalGap;
}
private CompositeStreamStrategy parseStreamStrategy(final CompositeStreamStrategy result,
Context context,
String authority)
throws IOException, XmlPullParserException {
final ProviderInfo info=
context.getPackageManager()
.resolveContentProvider(authority,
PackageManager.GET_META_DATA);
useLegacyCursorWrapper=info.metaData.getBoolean(META_DATA_USE_LEGACY_CURSOR_WRAPPER, true);
useUriForDataColumn=info.metaData.getBoolean(META_DATA_USE_URI_FOR_DATA_COLUMN, false);
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()) != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) {
if (type == org.xmlpull.v1.XmlPullParser.START_TAG) {
final String tag=in.getName();
if (!"paths".equals(tag)) {
final String name=in.getAttributeValue(null, ATTR_NAME);
if (TextUtils.isEmpty(name)) {
throw new IllegalArgumentException("Name must not be empty");
}
String path=in.getAttributeValue(null, ATTR_PATH);
boolean readOnly=allReadOnly ||
Boolean.parseBoolean(in.getAttributeValue(null, ATTR_READ_ONLY));
HashMap<String, String> attrs=new HashMap<String, String>();
for (int i=0;i<in.getAttributeCount();i++) {
attrs.put(in.getAttributeName(i), in.getAttributeValue(i));
}
StreamStrategy strategy=
buildStrategy(context, tag, name, path, readOnly, attrs);
if (strategy != null) {
result.add(name, strategy);
}
else {
throw new IllegalArgumentException("Could not build strategy for "
+ tag);
}
}
}
}
return(result);
}
/**
* Constructor.
*
* @param context The Context in which we are parsing the wallpaper.
* @param service The ResolveInfo returned from the package manager about
* this wallpaper's component.
*/
public WallpaperInfo(Context context, ResolveInfo service)
throws XmlPullParserException, IOException {
mService = service;
ServiceInfo si = service.serviceInfo;
final PackageManager pm = context.getPackageManager();
XmlResourceParser parser = null;
try {
parser = si.loadXmlMetaData(pm, WallpaperService.SERVICE_META_DATA);
if (parser == null) {
throw new XmlPullParserException("No "
+ WallpaperService.SERVICE_META_DATA + " meta-data");
}
Resources res = pm.getResourcesForApplication(si.applicationInfo);
AttributeSet attrs = Xml.asAttributeSet(parser);
int type;
while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
&& type != XmlPullParser.START_TAG) {
}
String nodeName = parser.getName();
if (!"wallpaper".equals(nodeName)) {
throw new XmlPullParserException(
"Meta-data does not start with wallpaper tag");
}
TypedArray sa = res.obtainAttributes(attrs,
com.android.internal.R.styleable.Wallpaper);
mSettingsActivityName = sa.getString(
com.android.internal.R.styleable.Wallpaper_settingsActivity);
mThumbnailResource = sa.getResourceId(
com.android.internal.R.styleable.Wallpaper_thumbnail,
-1);
mAuthorResource = sa.getResourceId(
com.android.internal.R.styleable.Wallpaper_author,
-1);
mDescriptionResource = sa.getResourceId(
com.android.internal.R.styleable.Wallpaper_description,
-1);
mContextUriResource = sa.getResourceId(
com.android.internal.R.styleable.Wallpaper_contextUri,
-1);
mContextDescriptionResource = sa.getResourceId(
com.android.internal.R.styleable.Wallpaper_contextDescription,
-1);
mShowMetadataInPreview = sa.getBoolean(
com.android.internal.R.styleable.Wallpaper_showMetadataInPreview,
false);
mSupportsAmbientMode = sa.getBoolean(
com.android.internal.R.styleable.Wallpaper_supportsAmbientMode,
false);
sa.recycle();
} catch (NameNotFoundException e) {
throw new XmlPullParserException(
"Unable to create context for: " + si.packageName);
} finally {
if (parser != null) parser.close();
}
}
/**
* Parse and return {@link PathStrategy} for given authority as defined in
* {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <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;
}
static void init(Context context) {
if (CMDS != null && SWS != null)
return;
final XmlResourceParser xml = context.getResources().getXml(
R.xml.apdu7816);
try {
// START__DOCUMENT
xml.next();
if (xml.next() == START_TAG
&& "apdu".equalsIgnoreCase(xml.getName())) {
while (xml.next() != END_DOCUMENT) {
Apdu7816 cmds = readTag(Apdu7816.CMDS.class, xml);
if (cmds != null) {
CMDS = cmds;
continue;
}
Apdu7816 sws = readTag(Apdu7816.SWS.class, xml);
if (sws != null) {
SWS = sws;
continue;
}
break;
}
}
} catch (Exception e) {
} finally {
if (xml != null)
xml.close();
}
if (CMDS == null)
CMDS = new Apdu7816.CMDS();
if (SWS == null)
SWS = new Apdu7816.SWS();
}
@Override
public long parseAndAdd(XmlResourceParser parser)
throws XmlPullParserException, IOException {
final String title;
final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
if (titleResId != 0) {
title = mSourceRes.getString(titleResId);
} else {
title = mContext.getResources().getString(R.string.folder_name);
}
mValues.put(Favorites.TITLE, title);
mValues.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
mValues.put(Favorites.SPANX, 1);
mValues.put(Favorites.SPANY, 1);
mValues.put(Favorites._ID, mCallback.generateNewItemId());
long folderId = mCallback.insertAndCheck(mDb, mValues);
if (folderId < 0) {
if (LOGD) Log.e(TAG, "Unable to add folder");
return -1;
}
final ContentValues myValues = new ContentValues(mValues);
ArrayList<Long> folderItems = new ArrayList<Long>();
int type;
int folderDepth = parser.getDepth();
while ((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > folderDepth) {
if (type != XmlPullParser.START_TAG) {
continue;
}
mValues.clear();
mValues.put(Favorites.CONTAINER, folderId);
TagParser tagParser = mFolderElements.get(parser.getName());
if (tagParser != null) {
final long id = tagParser.parseAndAdd(parser);
if (id >= 0) {
folderItems.add(id);
}
} else {
throw new RuntimeException("Invalid folder item " + parser.getName());
}
}
long addedId = folderId;
// We can only have folders with >= 2 items, so we need to remove the
// folder and clean up if less than 2 items were included, or some
// failed to add, and less than 2 were actually added
if (folderItems.size() < 2) {
// Delete the folder
Uri uri = Favorites.getContentUri(folderId, false);
SqlArguments args = new SqlArguments(uri, null, null);
mDb.delete(args.table, args.where, args.args);
addedId = -1;
// If we have a single item, promote it to where the folder
// would have been.
if (folderItems.size() == 1) {
final ContentValues childValues = new ContentValues();
copyInteger(myValues, childValues, Favorites.CONTAINER);
copyInteger(myValues, childValues, Favorites.SCREEN);
copyInteger(myValues, childValues, Favorites.CELLX);
copyInteger(myValues, childValues, Favorites.CELLY);
addedId = folderItems.get(0);
mDb.update(LauncherProvider.TABLE_FAVORITES, childValues,
Favorites._ID + "=" + addedId, null);
}
}
return addedId;
}
/**
* Parse and return {@link PathStrategy} for given authority as defined in
* {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <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;
}