Java web - analytical methods xml file read (DOM and SAX)

In fact, there are four ways to parse xml file: DOM, JDOM, DOM4J, SAX .
Our two official analytical methods for platform-independent: DOM and SAX

A, DOM parsing
in Java code, documentation xml file type is marked, with time to parse dom dom xml document assigns a tree structure in memory according to the hierarchical structure of html, the html tags, attributes, and text are encapsulated into an object

DOM parsing steps:
1. Using the newInstance method to create an object of a DocumentBuilderFactory.
2, the object creates a DocumentBuilde r, [] object DocumentBuilder parse through the
method of loading the xml file to the current project, such as:

DocumentBuilder db=dbf.newDocumentBuilder();

Document document=db.parse(uri);

3, get xml file

NodeList booklist = document.getElementsByTagName (node ​​name);

4, is traversed by a method foreach
5, Analytic node
NodeList childnode = book.getChildNodes (); available childnode.item (k) .getNodeType () == Node.ELEMENT_NODE this method to distinguish the determination of type text node and element type the node.

DOM parsing advantage: you can easily realize the function of additions and deletions to
the disadvantage: If the file is too large, causing memory overflow

Two, SAX parsing

In Java, SAX parsing event-driven, while being read resolution, from top to bottom, line by line parsing, parsing to a certain object, and returns the object name. And when SAX parsing the end, does not save any XML data document.

SAX parsing steps:
1. Create a SAXParserFactory object.

SAXParserFactory factory = SAXParserFactory.newInstance();

2, create a SAXParser object to load xml file by the parse method.

SAXParser parser = factory.newSAXParser();

Then there is the difference between the DOM need a handler, you will need to create a handler class.

3, handler class needs to inherit DefaultHandler.

SAX parsing advantage: If the file is too large, will not cause a memory overflow, easy to implement query;
drawback: You can not implement CRUD operations;

Guess you like

Origin www.cnblogs.com/jingxinbk/p/12458582.html