In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you the XML file parsing SAX/DOM/PULL example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to understand it!
Sax features (SAX is short for Simple API for XML)
1. High parsing efficiency and low memory consumption
two。 You can stop parsing at any time
3. Unable to load the entire document into memory
4. Cannot write to xml
5.SAX parses xml files using event-driven.
The differences between pull and sax
After reading the xml file, 1.pull triggers the corresponding event invocation method to return a number.
2.pull can be controlled in the program and can be stopped wherever you want to parse.
Pull parsing is more recommended in 3.Android.
Characteristics of DOM
Advantages
1. The whole document tree is in memory and easy to operate, and supports many functions such as deletion, modification, rearrangement and so on.
two。 Access xml documents through a tree structure
3. You can move forward or backward on a node in the tree
Shortcoming
1. Transfer the entire document to memory (including useless nodes), wasting time and space
Applicable occasion
Once the document has been parsed, the data needs to be accessed many times; there are plenty of hardware resources (memory, cpu)
First, define. I defined a Student.xml file.
* * example * *
[code] Xiaohong 21 female Shanghai Xiaohei 22 male Tianjin Xiaowang 23 male Beijing
* * 1.sax parsing * *
[code] package com.example.sax_xml;import java.io.IOException;import java.io.InputStream;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.InputSource;import org.xml.sax.XMLReader;import android.app.Activity;import android.content.res.AssetManager;import android.os.Bundle;import android.view.View;public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {/ / TODO Auto-generated method stub super.onCreate (savedInstanceState) SetContentView (R.layout.activity_main);} public void sax_xml (View v) {/ / get the device manager object AssetManager manager = this.getAssets (); try {/ / get the Student.xml file input stream InputStream is = manager.open ("Student.xml") in the assets directory / * SAXParserFactory defines an API factory so that applications can configure and obtain a parser based on SAX (Simple API for * XML * *) so that they can parse XML documents (original text: Defines a factory API that enables * applications to configure and obtain a SAX based parser to parse * XML documents. ) * * its constructor is protected, so the instance can only be obtained using the newInstance () method (Protected constructor to * force use of newInstance (). ) * / SAXParserFactory factory = SAXParserFactory.newInstance (); / * the XmlReader class is an abstract base class that provides non-cached, forward-only, read-only access to XML data. This class conforms to the recommendations of W3C Extensible markup language (XML) * 1.0 and namespaces in XML. The XmlReader class supports reading XML data from a stream or file. * the methods and properties defined by this class allow you to browse the data and read the contents of the node. The current node refers to the node on which the reader is located. * use any read methods and attributes that return the current node value to advance the reader. The XmlReader class enables you to: 1. Check to see if the character is a legal * XML character and that the names of elements and attributes are valid XML names. two。 Check that the XML document is in the correct format. 3. Validate data against DTD * or schema. 4. Retrieve data from the XML stream or use the extraction model to skip unwanted records. * / XMLReader xmlReader = factory.newSAXParser () .getXMLReader (); / * ContentHandler is a special SAX interface in the Java class package, which is located in the org.xml.sax package. This interface encapsulates some methods for event handling *. When the XML parser starts parsing the XML input document, it encounters some special events, such as the beginning and end of the document, the beginning and end of the element, and the character data in the element. When these events are encountered, the XML parser calls the appropriate methods in the ContentHandler interface to respond to the events. * / / because it is an interface, I directly write a class to inherit its subclass DefaultHandler and renew its method ContentHandler handler = new ContentHandler (); / / set the instance of ContentHandler to XMLReader / / setContentHandler this method sets the XML reader's content handler xmlReader.setContentHandler (handler) / / start parsing / / a single input source for the InputSource:XML entity. XmlReader.parse (new InputSource (is));} catch (Exception e) {/ / TODO Auto-generated catch block e.printStackTrace ();}
* * self-defined ContentHandler class * *
Import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import android.util.Log;public class ContentHandler extends DefaultHandler {private StringBuilder id; private StringBuilder name; private StringBuilder sex; private StringBuilder age; private StringBuilder adress; private String nodeName;// records the name of the current node / / calls @ Override public void startDocument () throws SAXException {id = new StringBuilder () when starting xml parsing. Name = new StringBuilder (); sex = new StringBuilder (); age = new StringBuilder (); adress = new StringBuilder ();} / / call @ Override public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {nodeName = localName when you start parsing a node } / / call @ Override public void characters (char [] ch, int start, int length) throws SAXException {if ("id" .equals (nodeName)) {id.append (ch, start, length);} else if ("name" .equals (nodeName)) {name.append (ch, start, length) when getting content in a node } else if ("age" .equals (nodeName)) {age.append (ch, start, length);} else if ("sex" .equals (nodeName)) {sex.append (ch, start, length);} else if ("adress" .equals (nodeName)) {adress.append (ch, start, length) }} / / call @ Override public void endElement (String uri, String localName, String qName) throws SAXException {if ("student" .equals (localName)) {Log.d ("ContentHandler", "id is" + id.toString (). Trim ()); Log.d ("ContentHandler", "name is" + name.toString (). Trim ()) Log.d ("ContentHandler", "age is" + age.toString (). Trim ()); Log.d ("ContentHandler", "sex is" + sex.toString (). Trim ()); Log.d ("ContentHandler", "adress is" + adress.toString (). Trim ()); / / finally, to empty id.setLength (0) from StringBuilder. Name.setLength (0); age.setLength (0); sex.setLength (0); adress.setLength (0);}} / / call @ Override public void endDocument () throws SAXException {/ / TODO Auto-generated method stub super.endDocument ();}} when the entire XML parsing is completed
* * 2.pull parsing * *
[code] package com.example.xmlpull;import android.app.Activity;import android.content.res.AssetManager;import android.os.Bundle;import android.util.Log;import android.util.Xml;import android.view.View;import android.widget.Toast;import org.xmlpull.v1.XmlPullParser;import java.io.InputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map / * the declaration of reading to xml returns the number 0 START_DOCUMENT; * the number 1 END_DOCUMENT is returned from reading to the end of xml * the opening tag read to xml returns the number 2 START_TAG * the end tag read to xml returns the number 3 END_TAG * the text read to xml returns the number 4 TEXT * / public class MainActivity extends Activity {/ * used to load parsed data * / private List oList; private Map oMap @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main);} public void btn_pull (View v) {/ / get device Manager object AssetManager manager = this.getAssets () Try {/ / get the Student.xml file input stream InputStream is = manager.open ("Student.xml") under the assets file; / / get the pull parsing object, whose constructor is protected, so you can only use the newInstance () method to get the instance XmlPullParser parser = Xml.newPullParser (). / / pass the xml file input stream to the pull parsing object parser.setInput (is, "UTF-8"); / / get the event type when parsing, int type = parser.getEventType () / / use the while loop. If the parsed event type is not equal to the last node type of the full-text document, always parse while (type! = XmlPullParser.END_DOCUMENT) {/ / to get the current node name String nodeName = parser.getName () Switch (type) {/ / if it is the start node type of the full document case XmlPullParser.START_DOCUMENT: / / initialize the collection of loaded data oList = new ArrayList (); break / / if it is the group start node type case XmlPullParser.START_TAG: / / judge if ("students" .equals (nodeName)) {} else if ("student" .equals (nodeName)) {oMap = new HashMap () based on the parsed node name / / get the student node at the beginning of group String id = parser.getAttributeValue (0); oMap.put ("id", id) } else if ("name" .equals (nodeName)) {/ / text corresponding to the node String name = parser.nextText (); oMap.put ("name", name) } else if ("sex" .equals (nodeName)) {String sex = parser.nextText (); oMap.put ("sex", sex);} else if ("age" .equals (nodeName)) {String age = parser.nextText () OMap.put ("age", age);} else if ("adress" .equals (nodeName)) {String adress = parser.nextText (); oMap.put ("adress", adress);} break / / to the last node of group: case XmlPullParser.END_TAG: if ("name" .equals (nodeName)) {Toast.makeText (this, "name resolution complete", Toast.LENGTH_LONG) .show () } if ("student" .equals (nodeName)) {oList.add (oMap);} break;} / / switch to the next group type = parser.next () }} catch (Exception e) {e.printStackTrace ();} / / finally traverses the collection Log for (int I = 0; I < oList.size ()) ITunes +) {Log.e ("error") "name:" + oList.get (I) .get ("name") + "- sex:" + oList.get (I) .get ("sex") + "- age:" + oList.get (I) .get ("age") + "- address:" + oList.get (I) .get ("adress")) }}}
First of all, let's talk about what we need to pay attention to in DOM parsing, because our teacher made this mistake when we were talking about it. Here's a special point.
Here, when we get the node student, which is drawn by the arrow in the figure, if we call its getChildNodes () method, can you guess how many child nodes it has? It does not include its grandchild node, except Xiao Hong, because it is a grandchild node. It has a total of five child nodes, each of which is marked with black lines in the figure. So when parsing, you must be careful not to ignore the white space.
The specific parsing code is attached below.
Here I split the parsing part of dom into a utility class.
[code] package com.example.domxml;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList / * Dom parsing is to load all the xml files and assemble them into a dom tree. * then parse the xml file through the nodes and the relationship between them, and dial * / public class Dom_xml_Util {private List list = new ArrayList () layer by layer. Public List getStudents (InputStream in) throws Exception {/ / gets the dom parsing factory, whose constructor is protected, so you can only get the instance DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance () with the newInstance () method; / / create a new DocumentBuilder instance / / DocumentBuilder with the currently configured parameters to get the DOM document instance from the DOM document. / / using this class, application programmers can get a Document DocumentBuilder builder = factory.newDocumentBuilder () from XML; / / get Document Document document = builder.parse (in); / / getDocumentElement () this is a convenient attribute that allows direct access to the child node / / Element interface of the document element of the document to represent an element in the HTML or XML document Element element = document.getDocumentElement (). / / returns the NodeList NodeList bookNodes = element.getElementsByTagName ("student") of all descendants of Elements with a given tag name in document order; / / traverses the number of nodes in the NodeList / / getLength () list for (int itemositi)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.