Home Backend Development XML/RSS Tutorial Be careful with the XmlPullParser.netText() method

Be careful with the XmlPullParser.netText() method

Feb 09, 2017 pm 01:58 PM

Using XmlPullParser on Android is a highly efficient and easy-to-maintain method of parsing XML. Android has historically had two implementation classes that implement this interface:

  • KXmlParser, via XmlPullParserFactory.newPullParser().

  • ExpatPullParser, via Xml.newPullParser().

There is a bug in the implementation of Xml.newPullParser() calling nextText(), nextText() is not always executed prior to END_TAG as mentioned in the documentation.

Therefore, some applications may have bugs in additional calls to next() or nextTag();

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

throws XmlPullParserException, IOException { 

    XmlPullParser parser = Xml.newPullParser(); 

    parser.setInput(reader); 

   

    parser.nextTag(); 

    parser.require(XmlPullParser.START_TAG, null, "menu"); 

    while (parser.nextTag() == XmlPullParser.START_TAG) { 

        parser.require(XmlPullParser.START_TAG, null, "item"); 

        String itemText = parser.nextText(); 

        parser.nextTag(); // this call shouldn’t be necessary! 

        parser.require(XmlPullParser.END_TAG, null, "item"); 

        System.out.println("menu option: " + itemText); 

    

    parser.require(XmlPullParser.END_TAG, null, "menu"); 

   

public static void main(String[] args) throws Exception { 

    new Menu().parseXml(new StringReader("<?xml version=&#39;1.0&#39;?>" 

            + "<menu>" 

            + "  <item>Waffles</item>" 

            + "  <item>Coffee</item>" 

            + "</menu>")); 

}

Copy after login

In android 4.0, Xml.newPullParser() has been changed to return the KxmlParser class, and at the same time Removed ExpatPullParser class. This fixes the nextTag() bug.

Unfortunately, the current applications that may crash are all versions lower than android 4.0. The following is the error message.

1

2

3

4

org.xmlpull.v1.XmlPullParserException: expected: END_TAG {null}item (position:START_TAG <item>@1:37 in java.io.StringReader@40442fa8)  

     at org.kxml2.io.KXmlParser.require(KXmlParser.java:2046) 

     at com.publicobject.waffles.Menu.parseXml(Menu.java:25) 

 at com.publicobject.waffles.Menu.main(Menu.java:32)

Copy after login

The solution is to jump to nextTag() only after calling nextText(), only when the current position is not END_TAG.

1

2

3

4

5

6

7

8

9

while (parser.nextTag() == XmlPullParser.START_TAG) { 

     parser.require(XmlPullParser.START_TAG, null, "item"); 

     String itemText = parser.nextText(); 

     if (parser.getEventType() != XmlPullParser.END_TAG) { 

         parser.nextTag(); 

     

     parser.require(XmlPullParser.END_TAG, null, "item"); 

     System.out.println("menu option: " + itemText); 

 }

Copy after login

The above code can correctly parse all xml versions. If the application uses nextText() extensively, use the following auxiliary method where nextText() is used.

1

2

3

4

5

6

7

8

private String safeNextText(XmlPullParser parser) 

         throws XmlPullParserException, IOException { 

     String result = parser.nextText(); 

     if (parser.getEventType() != XmlPullParser.END_TAG) { 

         parser.nextTag(); 

     

     return result; 

 }

Copy after login

Using a single XmlPullParse simplifies our maintenance and allows us to spend more energy on improving system performance.

The above is the content of the Be careful with the XmlPullParser.netText() method. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
RSS Document Tools: Building, Validating, and Publishing Feeds RSS Document Tools: Building, Validating, and Publishing Feeds Apr 09, 2025 am 12:10 AM

How to build, validate and publish RSSfeeds? 1. Build: Use Python scripts to generate RSSfeed, including title, link, description and release date. 2. Verification: Use FeedValidator.org or Python script to check whether RSSfeed complies with RSS2.0 standards. 3. Publish: Upload RSS files to the server, or use Flask to generate and publish RSSfeed dynamically. Through these steps, you can effectively manage and share content.

Is There an RSS Alternative Based on JSON? Is There an RSS Alternative Based on JSON? Apr 10, 2025 am 09:31 AM

JSONFeed is a JSON-based RSS alternative that has its advantages simplicity and ease of use. 1) JSONFeed uses JSON format, which is easy to generate and parse. 2) It supports dynamic generation and is suitable for modern web development. 3) Using JSONFeed can improve content management efficiency and user experience.

XML's Advantages in RSS: A Technical Deep Dive XML's Advantages in RSS: A Technical Deep Dive Apr 23, 2025 am 12:02 AM

XML has the advantages of structured data, scalability, cross-platform compatibility and parsing verification in RSS. 1) Structured data ensures consistency and reliability of content; 2) Scalability allows the addition of custom tags to suit content needs; 3) Cross-platform compatibility makes it work seamlessly on different devices; 4) Analytical and verification tools ensure the quality and integrity of the feed.

From XML to Readable Content: Demystifying RSS Feeds From XML to Readable Content: Demystifying RSS Feeds Apr 11, 2025 am 12:03 AM

RSSfeedsareXMLdocumentsusedforcontentaggregationanddistribution.Totransformthemintoreadablecontent:1)ParsetheXMLusinglibrarieslikefeedparserinPython.2)HandledifferentRSSversionsandpotentialparsingerrors.3)Transformthedataintouser-friendlyformatsliket

Building Feeds with XML: A Hands-On Guide to RSS Building Feeds with XML: A Hands-On Guide to RSS Apr 14, 2025 am 12:17 AM

The steps to build an RSSfeed using XML are as follows: 1. Create the root element and set the version; 2. Add the channel element and its basic information; 3. Add the entry element, including the title, link and description; 4. Convert the XML structure to a string and output it. With these steps, you can create a valid RSSfeed from scratch and enhance its functionality by adding additional elements such as release date and author information.

RSS Documents: How They Deliver Your Favorite Content RSS Documents: How They Deliver Your Favorite Content Apr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

Beyond the Basics: Advanced RSS Document Features Beyond the Basics: Advanced RSS Document Features Apr 21, 2025 am 12:03 AM

Advanced features of RSS include content namespaces, extension modules, and conditional subscriptions. 1) Content namespace extends RSS functionality, 2) Extended modules such as DublinCore or iTunes to add metadata, 3) Conditional subscription filters entries based on specific conditions. These functions are implemented by adding XML elements and attributes to improve information acquisition efficiency.

Creating RSS Documents: A Step-by-Step Tutorial Creating RSS Documents: A Step-by-Step Tutorial Apr 13, 2025 am 12:10 AM

The steps to create an RSS document are as follows: 1. Write in XML format, with the root element, including the elements. 2. Add, etc. elements to describe channel information. 3. Add elements, each representing a content entry, including,,,,,,,,,,,. 4. Optionally add and elements to enrich the content. 5. Ensure the XML format is correct, use online tools to verify, optimize performance and keep content updated.

See all articles