Java Code Examples for org.xmlpull.v1.XmlPullParser#getAttributeValue()

The following examples show how to use org.xmlpull.v1.XmlPullParser#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: Condition.java    From ssj with GNU General Public License v3.0 6 votes vote down vote up
public static Condition create(XmlPullParser xml, Context context)
{
    Condition b = null;
    String type = xml.getAttributeValue(null, "type");
    if (type != null && type.equalsIgnoreCase("SpeechRate"))
        b = new SpeechRate();
    else if (type != null && type.equalsIgnoreCase("Loudness"))
        b = new Loudness();
    else if (type != null && type.equalsIgnoreCase("KeyPress"))
        b = new KeyPress();
    else
        b = new Condition();

    b.load(xml, context);
    return b;
}
 
Example 2
Source File: TrustKitConfigurationParser.java    From TrustKit-Android with MIT License 6 votes vote down vote up
@NonNull
private static DomainTag readDomain(@NonNull XmlPullParser parser) throws IOException,
        XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, null, "domain");
    DomainTag result = new DomainTag();

    // Look for the includeSubdomains attribute
    String includeSubdomains = parser.getAttributeValue(null, "includeSubdomains");
    if (includeSubdomains != null) {
        result.includeSubdomains = Boolean.parseBoolean(includeSubdomains);
    }

    // Parse the domain text
    result.hostname = parser.nextText();
    return result;
}
 
Example 3
Source File: JobStore.java    From JobSchedulerCompat with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience function to read out and convert deadline and delay from xml into elapsed real
 * time.
 *
 * @return A {@link android.util.Pair}, where the first value is the earliest elapsed runtime
 * and the second is the latest elapsed runtime.
 */
private Pair<Long, Long> buildExecutionTimesFromXml(XmlPullParser parser)
        throws NumberFormatException {
    // Pull out execution time data.
    final long nowWallclock = System.currentTimeMillis();
    final long nowElapsed = SystemClock.elapsedRealtime();

    long earliestRunTimeElapsed = JobStatus.NO_EARLIEST_RUNTIME;
    long latestRunTimeElapsed = JobStatus.NO_LATEST_RUNTIME;
    String val = parser.getAttributeValue(null, "deadline");
    if (val != null) {
        long latestRuntimeWallclock = Long.valueOf(val);
        long maxDelayElapsed =
                Math.max(latestRuntimeWallclock - nowWallclock, 0);
        latestRunTimeElapsed = nowElapsed + maxDelayElapsed;
    }
    val = parser.getAttributeValue(null, "delay");
    if (val != null) {
        long earliestRuntimeWallclock = Long.valueOf(val);
        long minDelayElapsed =
                Math.max(earliestRuntimeWallclock - nowWallclock, 0);
        earliestRunTimeElapsed = nowElapsed + minDelayElapsed;

    }
    return Pair.create(earliestRunTimeElapsed, latestRunTimeElapsed);
}
 
Example 4
Source File: XmlUtils.java    From WeexOne with MIT License 5 votes vote down vote up
public static byte[] readByteArrayAttribute(XmlPullParser in, String name) {
    final String value = in.getAttributeValue(null, name);
    if (value != null) {
        return Base64.decode(value, Base64.DEFAULT);
    } else {
        return null;
    }
}
 
Example 5
Source File: DashManifestParser.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
protected int parseContentType(XmlPullParser xpp) {
  String contentType = xpp.getAttributeValue(null, "contentType");
  return TextUtils.isEmpty(contentType) ? C.TRACK_TYPE_UNKNOWN
      : MimeTypes.BASE_TYPE_AUDIO.equals(contentType) ? C.TRACK_TYPE_AUDIO
          : MimeTypes.BASE_TYPE_VIDEO.equals(contentType) ? C.TRACK_TYPE_VIDEO
              : MimeTypes.BASE_TYPE_TEXT.equals(contentType) ? C.TRACK_TYPE_TEXT
                  : C.TRACK_TYPE_UNKNOWN;
}
 
Example 6
Source File: SsManifestParser.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
protected final long parseLong(XmlPullParser parser, String key, long defaultValue)
    throws ParserException {
  String value = parser.getAttributeValue(null, key);
  if (value != null) {
    try {
      return Long.parseLong(value);
    } catch (NumberFormatException e) {
      throw new ParserException(e);
    }
  } else {
    return defaultValue;
  }
}
 
Example 7
Source File: SELinuxMMAC.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Loop over a signer tag looking for seinfo, package and cert tags. A {@link Policy}
 * instance will be created and returned in the process. During the pass all other
 * tag elements will be skipped.
 *
 * @param parser an XmlPullParser object representing a signer element.
 * @return the constructed {@link Policy} instance
 * @throws IOException
 * @throws XmlPullParserException
 * @throws IllegalArgumentException if any of the validation checks fail while
 *         parsing tag values.
 * @throws IllegalStateException if any of the invariants fail when constructing
 *         the {@link Policy} instance.
 */
private static Policy readSignerOrThrow(XmlPullParser parser) throws IOException,
        XmlPullParserException {

    parser.require(XmlPullParser.START_TAG, null, "signer");
    Policy.PolicyBuilder pb = new Policy.PolicyBuilder();

    // Check for a cert attached to the signer tag. We allow a signature
    // to appear as an attribute as well as those attached to cert tags.
    String cert = parser.getAttributeValue(null, "signature");
    if (cert != null) {
        pb.addSignature(cert);
    }

    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }

        String tagName = parser.getName();
        if ("seinfo".equals(tagName)) {
            String seinfo = parser.getAttributeValue(null, "value");
            pb.setGlobalSeinfoOrThrow(seinfo);
            readSeinfo(parser);
        } else if ("package".equals(tagName)) {
            readPackageOrThrow(parser, pb);
        } else if ("cert".equals(tagName)) {
            String sig = parser.getAttributeValue(null, "signature");
            pb.addSignature(sig);
            readCert(parser);
        } else {
            skip(parser);
        }
    }

    return pb.build();
}
 
Example 8
Source File: XmlUtils.java    From PreferenceFragment with Apache License 2.0 5 votes vote down vote up
public static long readLongAttribute(XmlPullParser in, String name) throws IOException {
    final String value = in.getAttributeValue(null, name);
    try {
        return Long.parseLong(value);
    } catch (NumberFormatException e) {
        throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
    }
}
 
Example 9
Source File: XmlUtils.java    From WeexOne with MIT License 5 votes vote down vote up
public static int readIntAttribute(XmlPullParser in, String name, int defaultValue) {
    final String value = in.getAttributeValue(null, name);
    try {
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        return defaultValue;
    }
}
 
Example 10
Source File: JobStore.java    From JobSchedulerCompat with Apache License 2.0 5 votes vote down vote up
private JobInfo.Builder buildBuilderFromXml(XmlPullParser parser) throws NumberFormatException {
    // Pull out required fields from <job> attributes.
    int jobId = Integer.valueOf(parser.getAttributeValue(null, "jobid"));
    String packageName = parser.getAttributeValue(null, "package");
    String className = parser.getAttributeValue(null, "class");
    ComponentName cname = new ComponentName(packageName, className);

    return new JobInfo.Builder(jobId, cname);
}
 
Example 11
Source File: MediaPresentationDescriptionParser.java    From Exoplayer_VLC with Apache License 2.0 5 votes vote down vote up
protected static long parseDuration(XmlPullParser xpp, String name, long defaultValue) {
  String value = xpp.getAttributeValue(null, name);
  if (value == null) {
    return defaultValue;
  } else {
    return Util.parseXsDuration(value);
  }
}
 
Example 12
Source File: KeySetManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
void readPublicKeyLPw(XmlPullParser parser)
        throws XmlPullParserException {
    String encodedID = parser.getAttributeValue(null, "identifier");
    long identifier = Long.parseLong(encodedID);
    int refCount = 0;
    String encodedPublicKey = parser.getAttributeValue(null, "value");
    PublicKey pub = PackageParser.parsePublicKey(encodedPublicKey);
    if (pub != null) {
        PublicKeyHandle pkh = new PublicKeyHandle(identifier, refCount, pub);
        mPublicKeys.put(identifier, pkh);
    }
}
 
Example 13
Source File: SsManifestParser.java    From K-Sonic with MIT License 5 votes vote down vote up
private int parseType(XmlPullParser parser) throws ParserException {
  String value = parser.getAttributeValue(null, KEY_TYPE);
  if (value != null) {
    if (KEY_TYPE_AUDIO.equalsIgnoreCase(value)) {
      return C.TRACK_TYPE_AUDIO;
    } else if (KEY_TYPE_VIDEO.equalsIgnoreCase(value)) {
      return C.TRACK_TYPE_VIDEO;
    } else if (KEY_TYPE_TEXT.equalsIgnoreCase(value)) {
      return C.TRACK_TYPE_TEXT;
    } else {
      throw new ParserException("Invalid key value[" + value + "]");
    }
  }
  throw new MissingFieldException(KEY_TYPE);
}
 
Example 14
Source File: XMLParser.java    From light-novel-library_Wenku8_Android with GNU General Public License v2.0 4 votes vote down vote up
static public ArrayList<NovelListWithInfo> getNovelListWithInfo(String xml) {
	try {
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		XmlPullParser xmlPullParser = factory.newPullParser();
		ArrayList<NovelListWithInfo> l = null;
		NovelListWithInfo n = null;
		xmlPullParser.setInput(new StringReader(xml));
		int eventType = xmlPullParser.getEventType();

		while (eventType != XmlPullParser.END_DOCUMENT) {
			switch (eventType) {
			case XmlPullParser.START_DOCUMENT:
				l = new ArrayList<NovelListWithInfo>();
				break;

			case XmlPullParser.START_TAG:

				if ("item".equals(xmlPullParser.getName())) {
					n = new NovelListWithInfo();
					n.aid = new Integer(xmlPullParser.getAttributeValue(0));
					// Log.v("MewX-XML", "aid=" + n.aid);
				} else if ("data".equals(xmlPullParser.getName())) {
					if ("Title".equals(xmlPullParser.getAttributeValue(0))) {
						n.name = xmlPullParser.nextText();
						// Log.v("MewX-XML", n.name);
					} else if ("TotalHitsCount".equals(xmlPullParser
							.getAttributeValue(0))) {
						n.hit = new Integer(
								xmlPullParser.getAttributeValue(1));
						// Log.v("MewX-XML", "hit=" + n.hit);
					} else if ("PushCount".equals(xmlPullParser
							.getAttributeValue(0))) {
						n.push = new Integer(
								xmlPullParser.getAttributeValue(1));
						// Log.v("MewX-XML", "push=" + n.push);
					} else if ("FavCount".equals(xmlPullParser
							.getAttributeValue(0))) {
						n.fav = new Integer(
								xmlPullParser.getAttributeValue(1));
						// Log.v("MewX-XML", "fav=" + n.fav);
					}
				}
				break;

			case XmlPullParser.END_TAG:
				if ("item".equals(xmlPullParser.getName())) {
					Log.v("MewX-XML", n.aid + ";" + n.name + ";" + n.hit
							+ ";" + n.push + ";" + n.fav);
					l.add(n);
					n = null;
				}
				break;
			}
			eventType = xmlPullParser.next();
		}
		return l;
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 15
Source File: DashManifestParser.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
protected RepresentationInfo parseRepresentation(
    XmlPullParser xpp,
    String baseUrl,
    String adaptationSetMimeType,
    String adaptationSetCodecs,
    int adaptationSetWidth,
    int adaptationSetHeight,
    float adaptationSetFrameRate,
    int adaptationSetAudioChannels,
    int adaptationSetAudioSamplingRate,
    String adaptationSetLanguage,
    List<Descriptor> adaptationSetRoleDescriptors,
    List<Descriptor> adaptationSetAccessibilityDescriptors,
    List<Descriptor> adaptationSetSupplementalProperties,
    SegmentBase segmentBase)
    throws XmlPullParserException, IOException {
  String id = xpp.getAttributeValue(null, "id");
  int bandwidth = parseInt(xpp, "bandwidth", Format.NO_VALUE);

  String mimeType = parseString(xpp, "mimeType", adaptationSetMimeType);
  String codecs = parseString(xpp, "codecs", adaptationSetCodecs);
  int width = parseInt(xpp, "width", adaptationSetWidth);
  int height = parseInt(xpp, "height", adaptationSetHeight);
  float frameRate = parseFrameRate(xpp, adaptationSetFrameRate);
  int audioChannels = adaptationSetAudioChannels;
  int audioSamplingRate = parseInt(xpp, "audioSamplingRate", adaptationSetAudioSamplingRate);
  String drmSchemeType = null;
  ArrayList<SchemeData> drmSchemeDatas = new ArrayList<>();
  ArrayList<Descriptor> inbandEventStreams = new ArrayList<>();
  ArrayList<Descriptor> supplementalProperties = new ArrayList<>();

  boolean seenFirstBaseUrl = false;
  do {
    xpp.next();
    if (XmlPullParserUtil.isStartTag(xpp, "BaseURL")) {
      if (!seenFirstBaseUrl) {
        baseUrl = parseBaseUrl(xpp, baseUrl);
        seenFirstBaseUrl = true;
      }
    } else if (XmlPullParserUtil.isStartTag(xpp, "AudioChannelConfiguration")) {
      audioChannels = parseAudioChannelConfiguration(xpp);
    } else if (XmlPullParserUtil.isStartTag(xpp, "SegmentBase")) {
      segmentBase = parseSegmentBase(xpp, (SingleSegmentBase) segmentBase);
    } else if (XmlPullParserUtil.isStartTag(xpp, "SegmentList")) {
      segmentBase = parseSegmentList(xpp, (SegmentList) segmentBase);
    } else if (XmlPullParserUtil.isStartTag(xpp, "SegmentTemplate")) {
      segmentBase =
          parseSegmentTemplate(
              xpp, (SegmentTemplate) segmentBase, adaptationSetSupplementalProperties);
    } else if (XmlPullParserUtil.isStartTag(xpp, "ContentProtection")) {
      Pair<String, SchemeData> contentProtection = parseContentProtection(xpp);
      if (contentProtection.first != null) {
        drmSchemeType = contentProtection.first;
      }
      if (contentProtection.second != null) {
        drmSchemeDatas.add(contentProtection.second);
      }
    } else if (XmlPullParserUtil.isStartTag(xpp, "InbandEventStream")) {
      inbandEventStreams.add(parseDescriptor(xpp, "InbandEventStream"));
    } else if (XmlPullParserUtil.isStartTag(xpp, "SupplementalProperty")) {
      supplementalProperties.add(parseDescriptor(xpp, "SupplementalProperty"));
    } else {
      maybeSkipTag(xpp);
    }
  } while (!XmlPullParserUtil.isEndTag(xpp, "Representation"));

  Format format =
      buildFormat(
          id,
          mimeType,
          width,
          height,
          frameRate,
          audioChannels,
          audioSamplingRate,
          bandwidth,
          adaptationSetLanguage,
          adaptationSetRoleDescriptors,
          adaptationSetAccessibilityDescriptors,
          codecs,
          supplementalProperties);
  segmentBase = segmentBase != null ? segmentBase : new SingleSegmentBase();

  return new RepresentationInfo(format, baseUrl, segmentBase, drmSchemeType, drmSchemeDatas,
      inbandEventStreams, Representation.REVISION_ID_DEFAULT);
}
 
Example 16
Source File: XMLParser.java    From light-novel-library_Wenku8_Android with GNU General Public License v2.0 4 votes vote down vote up
static public NovelFullInfo getNovelFullInfo(String xml) {
	try {
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		XmlPullParser xmlPullParser = factory.newPullParser();
		NovelFullInfo nfi = null;
		xmlPullParser.setInput(new StringReader(xml));
		int eventType = xmlPullParser.getEventType();

		while (eventType != XmlPullParser.END_DOCUMENT) {
			switch (eventType) {
			case XmlPullParser.START_DOCUMENT:
				break;

			case XmlPullParser.START_TAG:

				if ("metadata".equals(xmlPullParser.getName())) {
					nfi = new NovelFullInfo();
				} else if ("data".equals(xmlPullParser.getName())) {
					if ("Title".equals(xmlPullParser.getAttributeValue(0))) {
						nfi.aid = new Integer(
								xmlPullParser.getAttributeValue(1));
						nfi.title = xmlPullParser.nextText();
					} else if ("Author".equals(xmlPullParser
							.getAttributeValue(0))) {
						nfi.author = xmlPullParser.getAttributeValue(1);
					} else if ("DayHitsCount".equals(xmlPullParser
							.getAttributeValue(0))) {
						nfi.dayHitsCount = new Integer(xmlPullParser.getAttributeValue(1));
					} else if ("TotalHitsCount".equals(xmlPullParser
							.getAttributeValue(0))) {
						nfi.totalHitsCount = new Integer(xmlPullParser.getAttributeValue(1));
					} else if ("PushCount".equals(xmlPullParser
							.getAttributeValue(0))) {
						nfi.pushCount = new Integer(xmlPullParser.getAttributeValue(1));
					} else if ("FavCount".equals(xmlPullParser
							.getAttributeValue(0))) {
						nfi.favCount = new Integer(xmlPullParser.getAttributeValue(1));
					} else if ("PressId".equals(xmlPullParser
							.getAttributeValue(0))) {
						nfi.pressId = xmlPullParser.getAttributeValue(1);
					} else if ("BookStatus".equals(xmlPullParser
							.getAttributeValue(0))) {
						nfi.bookStatus = xmlPullParser.getAttributeValue(1);
					} else if ("BookLength".equals(xmlPullParser
							.getAttributeValue(0))) {
						nfi.bookLength = new Integer(xmlPullParser.getAttributeValue(1));
					} else if ("LastUpdate".equals(xmlPullParser
							.getAttributeValue(0))) {
						nfi.lastUpdate = xmlPullParser.getAttributeValue(1);
					} else if ("LatestSection".equals(xmlPullParser
							.getAttributeValue(0))) {
						nfi.latestSectionCid = new Integer(
								xmlPullParser.getAttributeValue(1));
						nfi.latestSectionName=xmlPullParser.nextText();
					}
				}
				break;
			}
			eventType = xmlPullParser.next();
		}
		return nfi;
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 17
Source File: ZenModeConfig.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public static ZenModeConfig readXml(XmlPullParser parser)
        throws XmlPullParserException, IOException {
    int type = parser.getEventType();
    if (type != XmlPullParser.START_TAG) return null;
    String tag = parser.getName();
    if (!ZEN_TAG.equals(tag)) return null;
    final ZenModeConfig rt = new ZenModeConfig();
    rt.version = safeInt(parser, ZEN_ATT_VERSION, XML_VERSION);
    rt.user = safeInt(parser, ZEN_ATT_USER, rt.user);
    boolean readSuppressedEffects = false;
    while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
        tag = parser.getName();
        if (type == XmlPullParser.END_TAG && ZEN_TAG.equals(tag)) {
            return rt;
        }
        if (type == XmlPullParser.START_TAG) {
            if (ALLOW_TAG.equals(tag)) {
                rt.allowCalls = safeBoolean(parser, ALLOW_ATT_CALLS,
                        DEFAULT_ALLOW_CALLS);
                rt.allowRepeatCallers = safeBoolean(parser, ALLOW_ATT_REPEAT_CALLERS,
                        DEFAULT_ALLOW_REPEAT_CALLERS);
                rt.allowMessages = safeBoolean(parser, ALLOW_ATT_MESSAGES,
                        DEFAULT_ALLOW_MESSAGES);
                rt.allowReminders = safeBoolean(parser, ALLOW_ATT_REMINDERS,
                        DEFAULT_ALLOW_REMINDERS);
                rt.allowEvents = safeBoolean(parser, ALLOW_ATT_EVENTS, DEFAULT_ALLOW_EVENTS);
                final int from = safeInt(parser, ALLOW_ATT_FROM, -1);
                final int callsFrom = safeInt(parser, ALLOW_ATT_CALLS_FROM, -1);
                final int messagesFrom = safeInt(parser, ALLOW_ATT_MESSAGES_FROM, -1);
                if (isValidSource(callsFrom) && isValidSource(messagesFrom)) {
                    rt.allowCallsFrom = callsFrom;
                    rt.allowMessagesFrom = messagesFrom;
                } else if (isValidSource(from)) {
                    Slog.i(TAG, "Migrating existing shared 'from': " + sourceToString(from));
                    rt.allowCallsFrom = from;
                    rt.allowMessagesFrom = from;
                } else {
                    rt.allowCallsFrom = DEFAULT_CALLS_SOURCE;
                    rt.allowMessagesFrom = DEFAULT_SOURCE;
                }
                rt.allowAlarms = safeBoolean(parser, ALLOW_ATT_ALARMS, DEFAULT_ALLOW_ALARMS);
                rt.allowMedia = safeBoolean(parser, ALLOW_ATT_MEDIA,
                        DEFAULT_ALLOW_MEDIA);
                rt.allowSystem = safeBoolean(parser, ALLOW_ATT_SYSTEM, DEFAULT_ALLOW_SYSTEM);

                // migrate old suppressed visual effects fields, if they still exist in the xml
                Boolean allowWhenScreenOff = unsafeBoolean(parser, ALLOW_ATT_SCREEN_OFF);
                if (allowWhenScreenOff != null) {
                    readSuppressedEffects = true;
                    if (allowWhenScreenOff) {
                        rt.suppressedVisualEffects |= SUPPRESSED_EFFECT_LIGHTS
                                | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
                    }
                }
                Boolean allowWhenScreenOn = unsafeBoolean(parser, ALLOW_ATT_SCREEN_ON);
                if (allowWhenScreenOn != null) {
                    readSuppressedEffects = true;
                    if (allowWhenScreenOn) {
                        rt.suppressedVisualEffects |= SUPPRESSED_EFFECT_PEEK;
                    }
                }
                if (readSuppressedEffects) {
                    Slog.d(TAG, "Migrated visual effects to " + rt.suppressedVisualEffects);
                }
            } else if (DISALLOW_TAG.equals(tag) && !readSuppressedEffects) {
                // only read from suppressed visual effects field if we haven't just migrated
                // the values from allowOn/allowOff, lest we wipe out those settings
                rt.suppressedVisualEffects = safeInt(parser, DISALLOW_ATT_VISUAL_EFFECTS,
                        DEFAULT_SUPPRESSED_VISUAL_EFFECTS);
            } else if (MANUAL_TAG.equals(tag)) {
                rt.manualRule = readRuleXml(parser);
            } else if (AUTOMATIC_TAG.equals(tag)) {
                final String id = parser.getAttributeValue(null, RULE_ATT_ID);
                final ZenRule automaticRule = readRuleXml(parser);
                if (id != null && automaticRule != null) {
                    automaticRule.id = id;
                    rt.automaticRules.put(id, automaticRule);
                }
            } else if (STATE_TAG.equals(tag)) {
                rt.areChannelsBypassingDnd = safeBoolean(parser,
                        STATE_ATT_CHANNELS_BYPASSING_DND, DEFAULT_CHANNELS_BYPASSING_DND);
            }
        }
    }
    throw new IllegalStateException("Failed to reach END_DOCUMENT");
}
 
Example 18
Source File: DashManifestParser.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
protected static long parseLong(XmlPullParser xpp, String name, long defaultValue) {
  String value = xpp.getAttributeValue(null, name);
  return value == null ? defaultValue : Long.parseLong(value);
}
 
Example 19
Source File: XMLParser.java    From light-novel-library_Wenku8_Android with GNU General Public License v2.0 4 votes vote down vote up
static public ArrayList<VolumeList> getVolumeList(String xml) {
	try {
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		XmlPullParser xmlPullParser = factory.newPullParser();
		ArrayList<VolumeList> l = null;
		VolumeList vl = null;
		ChapterInfo ci = null;
		xmlPullParser.setInput(new StringReader(xml));
		int eventType = xmlPullParser.getEventType();

		while (eventType != XmlPullParser.END_DOCUMENT) {
			switch (eventType) {
			case XmlPullParser.START_DOCUMENT:
				l = new ArrayList<VolumeList>();
				break;

			case XmlPullParser.START_TAG:

				if ("volume".equals(xmlPullParser.getName())) {
					vl = new VolumeList();
					vl.chapterList = new ArrayList<ChapterInfo>();
					vl.vid = new Integer(xmlPullParser.getAttributeValue(0));

					// Here the returned text has some format error
					// And I will handle them then
					Log.v("MewX-XML", "+ " + vl.vid + "; ");
				} else if ("chapter".equals(xmlPullParser.getName())) {
					ci = new ChapterInfo();
					ci.cid = new Integer(xmlPullParser.getAttributeValue(0));
					ci.chapterName = xmlPullParser.nextText();
					Log.v("MewX-XML", ci.cid + "; " + ci.chapterName);
					vl.chapterList.add(ci);
					ci = null;
				}
				break;

			case XmlPullParser.END_TAG:
				if ("volume".equals(xmlPullParser.getName())) {
					l.add(vl);
					vl = null;
				}
				break;
			}
			eventType = xmlPullParser.next();
		}

		/** Handle the rest problem */
		// Problem like this:
		// <volume vid="41748"><![CDATA[第一卷 告白于苍刻之夜]]>
		// <chapter cid="41749"><![CDATA[序章]]></chapter>
		int currentIndex = 0;
		for (int i = 0; i < l.size(); i++) {
			currentIndex = xml.indexOf("volume", currentIndex);
			if (currentIndex != -1) {
				currentIndex = xml.indexOf("CDATA[", currentIndex);
				if (xml.indexOf("volume", currentIndex) != -1) {
					int beg = currentIndex + 6;
					int end = xml.indexOf("]]", currentIndex);

					if (end != -1) {
						l.get(i).volumeName = xml.substring(beg, end);
						Log.v("MewX-XML", "+ " + l.get(i).volumeName + "; ");
						currentIndex = end + 1;
					} else
						break;

				} else
					break;
			} else
				break;
		}

		return l;
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 20
Source File: BluetoothXmlParser.java    From EFRConnect-android with Apache License 2.0 4 votes vote down vote up
private String readKey(XmlPullParser parser) {
    return parser.getAttributeValue(null, Consts.ATTRIBUTE_KEY);
}