Currently, two methods are used for XML parsing:
1. Dom parsing: (Document Object Model, that is, Document Object Model) is a method recommended by W3C for parsing XML.
Use Dom to parse an XML document. The parser first loads the XML document into the memory and generates the Document Object corresponding to the XML document, then, the tag elements in the XML document are converted into the corresponding element object, the text will become the Text object, and the attribute will become the attribute object, and save the relationships of these objects based on the relationships between the tags, text, and attributes in the XML document.
Disadvantage: memory consumption, so too many XML documents cannot be parsed when using Dom to parse XML documents; otherwise, memory overflow may occur.
Advantage: Using Dom to parse XML documents can easily perform addition, deletion, modification, and query operations (operations can be performed directly based on the object corresponding to the node ).
2. Sax parsing: Simple API for XML is not an official standard, but it is a de facto standard of the XML community. Almost all XML parsers support it.
Use Sax to parse XML documents. The parser reads from the top down, reads a row, and parses a row;
Advantage: Because it parses XML documents by reading a row and parsing a row, it will not put pressure on memory.
Disadvantage: it is not suitable for adding, deleting, modifying, and querying operations (it is also because it reads a row to parse a row when parsing the XML document, so it cannot perform back operations ), it is only suitable for reading XML documents.
========================================================== ========================================================== ======================================
Supplement:
XML parsing Development Kit: JAXP (Sun), JDOM, dom4j;
========================================================== ========================================================== ======================================
Adjust the JVM memory size:
When the memory of the XML file to be parsed is large and the node data in the XML file needs to be operated, it is obviously inconvenient to use these two parsing methods, in this case, you need to adjust the JVM memory size.
By default, the maximum memory capacity allowed by JVM is 64 mb. (the default maximum capacity value varies depending on JDK versions. JDK 170 is 64 MB, and JDK 7 is mb ).
To adjust the JVM memory size, run the following command:-xmx memory size unit ):
In the Eclipse project navigation box, right-click the corresponding Java program, run as, open run dialog...> open the run dialog box. Select the arguments option. There are two input boxes in the window. The first is the program parameter input box, and the second is the VM parameter input box, enter xmx200m In the parameter input box of the second Vm and click the run button in the lower right corner to execute the corresponding Java program. The error of outofmemoryerror will not be reported.
========================================================== ========================================================== ======================================
XML parsing development kit:
1. JAXP: The JAXP Development Kit is part of j2se. It consists of javax. XML, org. W3C. Dom, org. xml. Sax package and its sub-packages.
In javax. XML. the parsers package defines several factory classes. programmers can call these factory classes to obtain the Dom or SAX Parser of the XML document to parse the XML document.
First, create a factory:
Documentbuilderfactory factory = documentbuilderfactroy. newinstance (); // because the documentbuilderfactory class is an abstract class, its object cannot be new and can only be obtained by calling its static method.
Secondly, the DOM parser is obtained:
Documentbuilder builder = factory. newdocumentbuilder ();
Then, load the XML document to obtain the document object representing the document:
Document document = builder. parse ("*. xml ");
After obtaining the document object representing the XML document, you can operate on each node in the XML document.
========================================================== ========================================================== ======================================
Supplement:
In Dom parsing, each component of an XML document is represented by an object. For example, the tag uses element and attribute, but no matter what object is, it is a subclass of node, therefore, any node obtained can be treated as a node during development.
XML programming (crud)
Create, read, update, delete
Add, query, update, and delete;
In addition to the two parsing methods, there are also other parsing methods...
========================================================== ========================================================== ======================================
When adding, modifying, and deleting an XML document, you must update the document object and the XML document (rewrite the updated document object to the XML document ).
The transformer class in the javax. xml. Transform package is used to convert the document object representing the XML document into a certain format and then output it. For example, the XML document is converted into an HTML document after applying the style sheet. This object can also be used to re-write the document object to an XML document. Source and destination. You can use:
Javax. xml. Transform. Dom. domsource class to associate the document object to be converted,
Use the javax. xml. Transform. Stream. streamresult object to represent the data destination.
The transformer object is obtained through transformerfactory.
Transformer class completes the conversion operation through the transform method, which receives
(Transformerfactory) Transformer conversion method (domsource source, streamresult destination );))
========================================================== ========================================================== ======================================
Sax parsing:
The event processing method is used to parse XML files. The XML file is parsed using the sax method, which involves two parts: the parser and the event processor:
The parser can be created using the jaxp api. After creating a SAX Parser, you can specify a parser to parse an XML document.
When the parser parses an XML document using the sax method, it will call a method of the event processor as long as it is parsed to a specified part of the XML document, when the parser calls the method of the event processor, it will pass the content of the XML file currently parsed as a method parameter to the event processor.
The event processor is compiled by the programmer. The programmer can easily obtain the data parsed by the SAX Parser through the parameters of the method in the event processor, thus determining how to process the data.
1. Create a resolution factory;
Saxparserfactory FAC = saxparserfactory. newinstance ();
2. Get the parser;
Saxparser sp = FAC. newsaxparser ();
3. Get the reader;
Xmlreader Re = sp. getxmlreader ();
4. Set the content processor;
Re. setcontenthandler (New contenthandler () {/* code block implementing the interface */});
(Or: Re. setcontenthandler (New defaulthandler ();/* the parameter is a subclass of the defaulthandler class */)
The first method is to parse the entire XML document, and the second method can only parse a tag;
In fact, there is also a content processor that first inherits the defaulthandler class and then encapsulates the parsed content into the bean object.
5. Read XML documents;
Re. parse ("*. xml ");
========================================================== ========================================================== ======================================
XML parsing development kit:
2. dom4j:
Saxreader = new saxreader ();
Document Doc = saxreader. Read (new file ());
Outputformat format = outputformat. createprettyprint (); // This object indicates that the format is output in beautiful format. Another object is output in compact format;
Format. setencoding ("UTF-8 ");
Xmlwriter = new xmlwriter (New fileoutputstream (), format );
Xmlwriter. write (DOC); // If the xmlwriter object uses a byte stream, the object first converts the doc object to a byte according to the encoding format specified by the format object, then, the data is handed over to the byte stream for operation.
Writer. Close (); // closes the resource.
========================================================== ========================================================== ======================================
XPath:
You can use XPath to quickly locate a node;
List list = Document. selectnodes ("// Foo/Bar"); // obtain all bar nodes under the foo node;
Node node = Document. selectsinglenode ("// Foo/Bar"); // obtain the first bar node under the foo node;
A single slash is an absolute path starting from the root node;
A double slash is a relative path that starts from all current nodes;
The asterisk (*) indicates that all elements located in the path prior to the asterisk are selected;
For example:
/AA/BB/* indicates that all elements with paths attached to/AA/BB are selected;
/*/BBB indicates Selecting All BBB elements with three ancestor elements;
// BB [@ *] indicates selecting the BB element with any attribute;
// BB [not (@ *)] indicates that bb elements without attributes are selected;
// BB [@ ID = 'b1 '] indicates selecting the BB element containing the attribute id = 'b1;
XML parsing --- Dom parsing and sax Parsing