org.xmlpull.v1.XmlPullParser Java Examples

The following examples show how to use org.xmlpull.v1.XmlPullParser. 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: GenericXmlListTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * The purpose of this test is to map an XML with a {@link Collection} of {@link Integer} objects.
 */
@Test
public void testParseCollectionTypeInteger() throws Exception {
  CollectionTypeIntegerGeneric xml = new CollectionTypeIntegerGeneric();
  XmlPullParser parser = Xml.createParser();
  parser.setInput(new StringReader(MULTIPLE_INTEGER_ELEMENT));
  XmlNamespaceDictionary namespaceDictionary = new XmlNamespaceDictionary();
  Xml.parseElement(parser, xml, namespaceDictionary, null);
  // check type
  assertEquals(2, xml.rep.size());
  assertEquals(1, xml.rep.toArray(new Integer[] {})[0].intValue());
  assertEquals(2, xml.rep.toArray(new Integer[] {})[1].intValue());
  // serialize
  XmlSerializer serializer = Xml.createSerializer();
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  serializer.setOutput(out, "UTF-8");
  namespaceDictionary.serialize(serializer, "any", xml);
  assertEquals(MULTIPLE_INTEGER_ELEMENT, out.toString());
}
 
Example #2
Source File: ViewParser.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Process aspect definition
 * 
 * @param xpp XmlPullParser
 * @param aspectDef AspectDefinition
 * @param parserContext ParserContext
 * @throws XmlPullParserException
 * @throws IOException
 */
private void processAspect(XmlPullParser xpp, AspectDefinition aspectDef, ParserContext parserContext)
    throws XmlPullParserException, IOException
{
    NodeContext node = peekNodeContext(parserContext.elementStack);
    node.addAspect(aspectDef);
    
    int eventType = xpp.next();
    if (eventType != XmlPullParser.END_TAG)
    {
        throw new ImporterException("Aspect " + aspectDef.getName() + " definition is not valid - it cannot contain any elements");
    }
    
    if (logger.isDebugEnabled())
        logger.debug(indentLog("Processed aspect " + aspectDef.getName(), parserContext.elementStack.size()));
}
 
Example #3
Source File: WifiConfigStoreParser.java    From WiFiKeyShare with GNU General Public License v3.0 6 votes vote down vote up
public static List<WifiNetwork> parse(InputStream in)
        throws XmlPullParserException, IOException {
    List<WifiNetwork> wifiNetworks = new ArrayList<>();

    try {
        XmlPullParser parser = Xml.newPullParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(in, null);
        while (parser.next() != XmlPullParser.END_DOCUMENT) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            if (parser.getName().equalsIgnoreCase("NetworkList")) {
                wifiNetworks.addAll(readNetworkList(parser));
            }
        }
        return wifiNetworks;
    } finally {
        in.close();
    }
}
 
Example #4
Source File: GPXParser.java    From android-gpx-parser with Apache License 2.0 6 votes vote down vote up
private Copyright readCopyright(XmlPullParser parser) throws XmlPullParserException, IOException {
    parser.require(XmlPullParser.START_TAG, namespace, TAG_COPYRIGHT);

    Copyright.Builder copyrightBuilder = new Copyright.Builder();
    copyrightBuilder.setAuthor(parser.getAttributeValue(namespace, TAG_AUTHOR));

    while (loopMustContinue(parser.next())) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String name = parser.getName();
        switch (name) {
            case TAG_YEAR:
                copyrightBuilder.setYear(readYear(parser));
                break;
            case TAG_LICENSE:
                copyrightBuilder.setLicense(readString(parser, TAG_LICENSE));
                break;
            default:
                skip(parser);
                break;
        }
    }
    parser.require(XmlPullParser.END_TAG, namespace, TAG_COPYRIGHT);
    return copyrightBuilder.build();
}
 
Example #5
Source File: KeyboardLayoutSet.java    From LokiBoard-Android-Keylogger with Apache License 2.0 6 votes vote down vote up
private void parseKeyboardLayoutSetElement(final XmlPullParser parser)
        throws XmlPullParserException, IOException {
    final TypedArray a = mResources.obtainAttributes(Xml.asAttributeSet(parser),
            R.styleable.KeyboardLayoutSet_Element);
    try {
        XmlParseUtils.checkAttributeExists(a,
                R.styleable.KeyboardLayoutSet_Element_elementName, "elementName",
                TAG_ELEMENT, parser);
        XmlParseUtils.checkAttributeExists(a,
                R.styleable.KeyboardLayoutSet_Element_elementKeyboard, "elementKeyboard",
                TAG_ELEMENT, parser);
        XmlParseUtils.checkEndTag(TAG_ELEMENT, parser);

        final ElementParams elementParams = new ElementParams();
        final int elementName = a.getInt(
                R.styleable.KeyboardLayoutSet_Element_elementName, 0);
        elementParams.mKeyboardXmlId = a.getResourceId(
                R.styleable.KeyboardLayoutSet_Element_elementKeyboard, 0);
        elementParams.mAllowRedundantMoreKeys = a.getBoolean(
                R.styleable.KeyboardLayoutSet_Element_allowRedundantMoreKeys, true);
        mParams.mKeyboardLayoutSetElementIdToParamsMap.put(elementName, elementParams);
    } finally {
        a.recycle();
    }
}
 
Example #6
Source File: XmlUtils.java    From HeadsUp with GNU General Public License v2.0 6 votes vote down vote up
public static void beginDocument(XmlPullParser parser, String firstElementName)
        throws XmlPullParserException, IOException {
    int type;
    //noinspection StatementWithEmptyBody
    while ((type = parser.next()) != XmlPullParser.START_TAG
            && type != XmlPullParser.END_DOCUMENT) ;

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

    if (!parser.getName().equals(firstElementName)) {
        throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
                ", expected " + firstElementName);
    }
}
 
Example #7
Source File: XMLTVParser.java    From ChannelSurfer with MIT License 6 votes vote down vote up
public static List<Program> parse(String in) throws XmlPullParserException, IOException {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser xpp = factory.newPullParser();
            Log.d(TAG, "Start parsing");
            Log.d(TAG, in.substring(0, 36));
            xpp.setInput(new StringReader(in));
            int eventType = xpp.getEventType();
            Log.d(TAG, eventType+"");
//            if(eventType == XmlPullParser.START_DOCUMENT)
//                xpp.next();
            /*
            xpp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            xpp.setInput(new InputStreamReader(in));*/
            /*xpp.nextTag();
            xpp.nextTag();
            */return readFeed(xpp);
        } finally {
//            in.close();
        }
    }
 
Example #8
Source File: ResultProperties.java    From microMathematics with GNU General Public License v3.0 6 votes vote down vote up
public void readFromXml(XmlPullParser parser)
{
    String attr = parser.getAttributeValue(null, XML_PROP_DISABLE_CALCULATION);
    if (attr != null)
    {
        disableCalculation = Boolean.parseBoolean(attr);
    }
    attr = parser.getAttributeValue(null, XML_PROP_HIDE_RESULT_FIELD);
    if (attr != null)
    {
        hideResultField = Boolean.parseBoolean(attr);
    }
    attr = parser.getAttributeValue(null, XML_PROP_ARRAY_LENGTH);
    if (attr != null)
    {
        arrayLength = Integer.parseInt(attr);
    }
    attr = parser.getAttributeValue(null, XML_PROP_UNITS);
    if (attr != null)
    {
        units = attr;
    }
}
 
Example #9
Source File: ComponentDescription.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 *
 */
private static void skip(XmlPullParser p)
  throws IOException, XmlPullParserException
{
  int level = 0;
  int event = p.getEventType();

  while (event != XmlPullParser.END_DOCUMENT) {
    if (event == XmlPullParser.START_TAG) {
      level++;
    } else if (event == XmlPullParser.END_TAG) {
      level--;
      if (level <= 0) {
        p.next(); // jump beyond stopping tag.
        break;
      }
    }
    event = p.next();
  }
}
 
Example #10
Source File: FontsReaderApi21.java    From ProjectX with Apache License 2.0 6 votes vote down vote up
protected void startAlias(XmlPullParser parser) {
    // alias
    final String name = parser.getAttributeValue(null, ATTR_NAME);
    if (TextUtils.isEmpty(name))
        return;
    final String to = parser.getAttributeValue(null, ATTR_TO);
    if (TextUtils.isEmpty(to))
        return;
    int weight;
    try {
        weight = Integer.parseInt(parser.getAttributeValue(null, ATTR_WEIGHT));
    } catch (Exception e) {
        weight = -1;
    }
    mAlias = new Alias(name, to, weight);
}
 
Example #11
Source File: XmlUtils.java    From cwac-netsecurity with Apache License 2.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 IOException
 * 
 * @see #readSetXml
 * @hide
 */
private static final HashSet readThisSetXml(XmlPullParser parser, String endTag, String[] name,
        ReadMapCallback callback, boolean arrayMap)
        throws XmlPullParserException, IOException {
    HashSet set = new HashSet();
    
    int eventType = parser.getEventType();
    do {
        if (eventType == parser.START_TAG) {
            Object val = readThisValueXml(parser, name, callback, arrayMap);
            set.add(val);
            //System.out.println("Adding to set: " + val);
        } else if (eventType == parser.END_TAG) {
            if (parser.getName().equals(endTag)) {
                return set;
            }
            throw new XmlPullParserException(
                    "Expected " + endTag + " end tag at: " + parser.getName());
        }
        eventType = parser.next();
    } while (eventType != parser.END_DOCUMENT);
    
    throw new XmlPullParserException(
            "Document ended before " + endTag + " end tag");
}
 
Example #12
Source File: XmlUtils.java    From TowerCollector with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Read a flattened object from an XmlPullParser.  The XML data could
 * previously have been written with writeMapXml(), writeListXml(), or
 * writeValueXml().  The XmlPullParser must be positioned <em>at</em> the
 * tag that defines the value.
 *
 * @param parser The XmlPullParser from which to read the object.
 * @param name An array of one string, used to return the name attribute
 *             of the value's tag.
 *
 * @return Object The newly generated value object.
 *
 * @see #readMapXml
 * @see #readListXml
 * @see #writeValueXml
 */
public static final Object readValueXml(XmlPullParser parser, String[] name)
        throws XmlPullParserException, java.io.IOException
{
    int eventType = parser.getEventType();
    do {
        if (eventType == parser.START_TAG) {
            return readThisValueXml(parser, name);
        } else if (eventType == parser.END_TAG) {
            throw new XmlPullParserException(
                    "Unexpected end tag at: " + parser.getName());
        } else if (eventType == parser.TEXT) {
            throw new XmlPullParserException(
                    "Unexpected text: " + parser.getText());
        }
        eventType = parser.next();
    } while (eventType != parser.END_DOCUMENT);

    throw new XmlPullParserException(
            "Unexpected end of document");
}
 
Example #13
Source File: Dsmlv2ResponseParser.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Processes the task required in the grammar to the given tag type
 *
 * @param container the DSML container
 * @param tagType the tag type
 * @throws XmlPullParserException when an error occurs during the parsing
 */
private static void processTag( Dsmlv2Container container, int tagType ) throws XmlPullParserException
{
    XmlPullParser xpp = container.getParser();

    String tagName = Strings.lowerCase( xpp.getName() );

    GrammarTransition transition = container.getTransition( container.getState(), new Tag( tagName, tagType ) );

    if ( transition != null )
    {
        container.setState( transition.getNextState() );

        if ( transition.hasAction() )
        {
            transition.getAction().action( container );
        }
    }
    else
    {
        throw new XmlPullParserException( I18n.err( I18n.ERR_03036_MISSING_TAG, new Tag( tagName, tagType ) ), xpp, null );
    }
}
 
Example #14
Source File: XmlParser.java    From react-native-3d-model-view with MIT License 6 votes vote down vote up
private static void loadNode(XmlPullParser xpp, XmlNode parentNode) throws XmlPullParserException, IOException {
	int eventType = xpp.next();
	while(eventType != XmlPullParser.END_DOCUMENT) {
		if (eventType == XmlPullParser.START_TAG) {
			XmlNode childNode = new XmlNode(xpp.getName());
			for (int i=0; i<xpp.getAttributeCount(); i++){
				childNode.addAttribute(xpp.getAttributeName(i), xpp.getAttributeValue(i));
			}
			parentNode.addChild(childNode);
			loadNode(xpp, childNode);
		} else if (eventType == XmlPullParser.END_TAG) {
			return;
		} else if (eventType == XmlPullParser.TEXT) {
			parentNode.setData(xpp.getText());
		}
		eventType = xpp.next();
	}
}
 
Example #15
Source File: PackageStatusStorage.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@GuardedBy("this")
private PackageStatus getPackageStatusLocked() throws ParseException {
    try (FileInputStream fis = mPackageStatusFile.openRead()) {
        XmlPullParser parser = parseToPackageStatusTag(fis);
        Integer checkStatus = getNullableIntAttribute(parser, ATTRIBUTE_CHECK_STATUS);
        if (checkStatus == null) {
            return null;
        }
        int updateAppVersion = getIntAttribute(parser, ATTRIBUTE_UPDATE_APP_VERSION);
        int dataAppVersion = getIntAttribute(parser, ATTRIBUTE_DATA_APP_VERSION);
        return new PackageStatus(checkStatus,
                new PackageVersions(updateAppVersion, dataAppVersion));
    } catch (IOException e) {
        ParseException e2 = new ParseException("Error reading package status", 0);
        e2.initCause(e);
        throw e2;
    }
}
 
Example #16
Source File: FontsReaderApi26.java    From ProjectX with Apache License 2.0 6 votes vote down vote up
protected void startAxis(XmlPullParser parser) {
    // axis
    final String tag = parser.getAttributeValue(null, ATTR_TAG);
    if (TextUtils.isEmpty(tag))
        return;
    float value;
    try {
        value = Float.parseFloat(
                parser.getAttributeValue(null, ATTR_STYLEVALUE));
    } catch (Exception e) {
        return;
    }
    if (Axis.TAG_ITAL.equals(tag) || Axis.TAG_OPSZ.equals(tag) ||
            Axis.TAG_SLNT.equals(tag) || Axis.TAG_WDTH.equals(tag) ||
            Axis.TAG_WGHT.equals(tag))
        mAxis = new Axis(tag, value);
}
 
Example #17
Source File: SimpleXmlParser.java    From ssj with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param in               InputStream
 * @param searchPath       String[]
 * @param searchAttributes String[]
 * @return XmlValues
 * @throws XmlPullParserException
 * @throws IOException
 */
public XmlValues parse(InputStream in, String[] searchPath, String[] searchAttributes) throws XmlPullParserException, IOException
{
    this.searchPath = searchPath;
    this.searchAttributes = searchAttributes;
    xmlValues = new XmlValues();
    try
    {
        XmlPullParser parser = Xml.newPullParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(in, null);
        parser.nextTag();
        search(parser, 0);
        return xmlValues;
    } finally
    {
        in.close();
    }
}
 
Example #18
Source File: XmlUtils.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
public static final void nextElement(XmlPullParser parser) throws XmlPullParserException, IOException
{
    int type;
    while ((type=parser.next()) != parser.START_TAG
               && type != parser.END_DOCUMENT) {
        ;
    }
}
 
Example #19
Source File: ResourcesParser.java    From Stringlate with MIT License 5 votes vote down vote up
private static boolean readFirstBooleanAttr(XmlPullParser parser, String[] attrs, boolean defaultV) {
    for (String attr : attrs) {
        String value = parser.getAttributeValue(null, attr);
        if (value != null) {
            return Boolean.parseBoolean(value);
        }
    }

    return defaultV;
}
 
Example #20
Source File: Xpp3DomBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @deprecated As of 1.4, use {@link XppDom#build(XmlPullParser)} instead
 */
public static Xpp3Dom build(Reader reader) throws Exception {
    XmlPullParser parser = new MXParser();
    parser.setInput(reader);
    try {
        return (Xpp3Dom)XppDom.build(parser);
    } finally {
        reader.close();
    }
}
 
Example #21
Source File: XmlUtils.java    From WeexOne with MIT License 5 votes vote down vote up
public static boolean readBooleanAttribute(XmlPullParser in, String name,
                                           boolean defaultValue) {
    final String value = in.getAttributeValue(null, name);
    if (value == null) {
        return defaultValue;
    } else {
        return Boolean.parseBoolean(value);
    }
}
 
Example #22
Source File: KmlStyleParser.java    From android-maps-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the hot spot for the icon
 *
 * @param style Style object to apply hotspot properties to
 */
private static void setIconHotSpot(XmlPullParser parser, KmlStyle style)
        throws XmlPullParserException {
    if (parser.isEmptyElementTag()) {
        return;
    }
    float xValue, yValue;
    String xUnits, yUnits;
    xValue = Float.parseFloat(parser.getAttributeValue(null, "x"));
    yValue = Float.parseFloat(parser.getAttributeValue(null, "y"));
    xUnits = parser.getAttributeValue(null, "xunits");
    yUnits = parser.getAttributeValue(null, "yunits");
    style.setHotSpot(xValue, yValue, xUnits, yUnits);
}
 
Example #23
Source File: FeedParser.java    From Focus with GNU General Public License v3.0 5 votes vote down vote up
private static String readPubDate(XmlPullParser parser) throws IOException, XmlPullParserException {
        String pubData = readTagByTagName(parser,PUB_DATE);
        //TODO:对没有时间的feedItem 进行特殊处理
        if (pubData==null){
            pubData =DateUtil.getNowDateRFCStr();
        }
//        ALog.d("没有时间!");
//        ALog.d(pubData);
        return pubData;
    }
 
Example #24
Source File: MediaPresentationDescriptionParser.java    From Exoplayer_VLC with Apache License 2.0 5 votes vote down vote up
protected static Uri parseBaseUrl(XmlPullParser xpp, Uri parentBaseUrl)
    throws XmlPullParserException, IOException {
  xpp.next();
  String newBaseUrlText = xpp.getText();
  Uri newBaseUri = Uri.parse(newBaseUrlText);
  if (!newBaseUri.isAbsolute()) {
    newBaseUri = Uri.withAppendedPath(parentBaseUrl, newBaseUrlText);
  }
  return newBaseUri;
}
 
Example #25
Source File: XMLResponseHandler.java    From coursera-android with MIT License 5 votes vote down vote up
@Override
public List<String> handleResponse(HttpResponse response)
		throws ClientProtocolException, IOException {
	try {

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

		// Set the Parser's input to be the XML document in the HTTP Response
		xpp.setInput(new InputStreamReader(response.getEntity()
				.getContent()));
		
		// 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 e) {
	}
	return null;
}
 
Example #26
Source File: XmlPullParserUtil.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the value of an attribute of the current start tag. Any raw attribute names in the
 * current start tag have their prefixes stripped before matching.
 *
 * @param xpp The {@link XmlPullParser} to query.
 * @param attributeName The name of the attribute.
 * @return The value of the attribute, or null if the current event is not a start tag or if no
 *     such attribute was found.
 */
public static @Nullable String getAttributeValueIgnorePrefix(
    XmlPullParser xpp, String attributeName) {
  int attributeCount = xpp.getAttributeCount();
  for (int i = 0; i < attributeCount; i++) {
    if (stripPrefix(xpp.getAttributeName(i)).equals(attributeName)) {
      return xpp.getAttributeValue(i);
    }
  }
  return null;
}
 
Example #27
Source File: WISPAccessGatewayParam.java    From WiFiAfterConnect with Apache License 2.0 5 votes vote down vote up
private static String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
    String result = "";
    if (parser.next() == XmlPullParser.TEXT) {
        result = parser.getText();
        parser.nextTag();
    }
    return result;
}
 
Example #28
Source File: ChatTranscripts.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Reads in the transcript file using the Xml Pull Parser.
 *
 * @param transcriptFile the transcript file to read.
 * @return the ChatTranscript.
 */
public static ChatTranscript getTranscript(File transcriptFile) {
    final ChatTranscript transcript = new ChatTranscript();
    if (!transcriptFile.exists()) {
        return transcript;
    }

    try {
        final MXParser parser = new MXParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(transcriptFile), "UTF-8"));
        parser.setInput(in);
        boolean done = false;
        while (!done) {
            int eventType = parser.next();
            if (eventType == XmlPullParser.START_TAG && "message".equals(parser.getName())) {
                transcript.addHistoryMessage(getHistoryMessage(parser));
            }
            else if (eventType == XmlPullParser.END_TAG && "transcript".equals(parser.getName())) {
                done = true;
            }
        }
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
  

    return transcript;
}
 
Example #29
Source File: XmlUtils.java    From android-job with Apache License 2.0 5 votes vote down vote up
public static float readFloatAttribute(XmlPullParser in, String name) throws IOException {
    final String value = in.getAttributeValue(null, name);
    try {
        return Float.parseFloat(value);
    } catch (NumberFormatException e) {
        throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
    }
}
 
Example #30
Source File: XmlUtils.java    From HeadsUp with GNU General Public License v2.0 5 votes vote down vote up
public static float readFloatAttribute(XmlPullParser in, String name) throws IOException {
    final String value = in.getAttributeValue(null, name);
    try {
        return Float.parseFloat(value);
    } catch (NumberFormatException e) {
        throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
    }
}