Be careful with the XmlPullParser.netText() method
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();
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='1.0'?>"
+ "<menu>"
+ " <item>Waffles</item>"
+ " <item>Coffee</item>"
+ "</menu>"));
}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.
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)The solution is to jump to nextTag() only after calling nextText(), only when the current position is not END_TAG.
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);
}The above code can correctly parse all xml versions. If the application uses nextText() extensively, use the following auxiliary method where nextText() is used.
private String safeNextText(XmlPullParser parser)
throws XmlPullParserException, IOException {
String result = parser.nextText();
if (parser.getEventType() != XmlPullParser.END_TAG) {
parser.nextTag();
}
return result;
}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 (m.sbmmt.com)!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
XML Namespace: The most common Errors
Jun 27, 2025 am 01:00 AM
XMLnamespacescancauseerrors,butthesecanberesolvedbyfollowingspecificsteps.1)Alwaysdeclarethenamespaceusingxmlnsattherootorwhereneeded.2)Ensureprefixesmatchthedeclarednamespaces.3)Useuniqueprefixesfordifferentnamespacestoavoidconflicts.4)Properlydecla
XML: Are Namespaces required?
Jul 01, 2025 am 12:05 AM
XMLnamespacesarenotalwaysrequired,buttheyareessentialincertainsituations.1)TheyhelppreventnameconflictsinXMLdocumentscombiningelementsfrommultiplesources.2)Theycanbeomittedinsmall,self-containeddocuments.3)Bestpracticesincludeusingmeaningfulprefixesa
XML: Which are the best alternatives?
Jul 01, 2025 am 12:12 AM
JSON,YAML,ProtocolBuffers,CSV,andTOMLaresuitablealternativestoXML.1)JSONisidealforreadabilityandeaseofuse.2)YAMLofferscleanersyntaxandsupportscomments.3)ProtocolBuffersexcelinhigh-performanceapplications.4)CSVisperfectforsimpledataexchange.5)TOMLbala
Why XML Is Still Relevant: Exploring Its Strengths for Data Exchange
Jul 05, 2025 am 12:17 AM
XMLremainsrelevantduetoitsstructuredandself-describingnature.Itexcelsinindustriesrequiringprecisionandclarity,supportscustomtagsandschemas,andintegratesdatavianamespaces,thoughitcanbeverboseandresource-intensive.
XML Basic Rules: Ensuring Well-Formed and Valid XML
Jul 06, 2025 am 12:59 AM
XMLmustbewell-formedandvalid:1)Well-formedXMLfollowsbasicsyntacticruleslikeproperlynestedandclosedtags.2)ValidXMLadherestospecificrulesdefinedbyDTDsorXMLSchema,ensuringdataintegrityandconsistencyacrossapplications.
XML: Does encoding affects the well-formed status?
Jul 03, 2025 am 12:29 AM
XMLencodingdoesaffectwhetheradocumentisconsideredwell-formed.1)TheencodingmustbecorrectlydeclaredintheXMLdeclaration,matchingtheactualdocumentencoding.2)OmittingthedeclarationdefaultstoUTF-8orUTF-16,whichcanleadtoissuesifthedocumentusesadifferentenco
XML in Software Development: Use Cases and Reasons for Adoption
Jul 10, 2025 pm 12:14 PM
XMLischosenoverotherformatsduetoitsflexibility,human-readability,androbustecosystem.1)Itexcelsindataexchangeandconfiguration.2)It'splatform-independent,supportingintegrationacrossdifferentsystemsandlanguages.3)XML'sschemavalidationensuresdataintegrit
XML Schema: A Comprehensive Guide to Validating XML Documents
Jun 24, 2025 am 12:03 AM
XMLSchemaiscrucialforvalidatingXMLdocumentsbecauseitensuresdataintegrityandconsistencyacrosssystems.1)ItdefinesthestructureandrulesforXMLdocuments,actingasablueprint.2)XMLSchemaallowsforcomplexvalidationsandenforcesspecificdatarules.3)Itsupportsadvan


