When using Dom to parse XML documents, you need to read the entire XML document, and then create a DOM tree in the memory to generate each node object on the DOM tree. Other operations can be performed only after the entire DOM tree is created, even if we only need to modify the second subnode of the root element node, you still need to analyze the entire document between this small modification and build the document tree in the memory. When the XML document is large, it takes a lot of time and memory to build the DOM tree.
An alternative technology is to use SAX, which allows you to process a document when reading it, and the parsing is complete, you do not have to wait until the entire document is analyzed and stored.
Three-Step Process
To use the information in the XML file, you must parse the file to create a document object.
The document object is an interface (?? So it cannot be instantiated directly; normally, an application will use a factory accordingly. The accurate process varies by implementation, but the basic idea is the same. (Similarly, Level 3 standardizes this task .) In this Java environment, parsing a file is a three-step process:
1. Create documentbuilderfactory. The documentbuilderfactory object creates documentbuilder.
2. Create documentbuilder. Documentbuilder performs the actual parsing to create a document object.
3. parse the file to create a document object.
Now you can build the application.
Basic Applications
First, create a basic application, that is, a class named orderprocessor.
『『『『
The first step is to generate a documentbuilderfactory object. newinstance () is a static method, so you can call it directly by class name.
The second step is to use the factory to generate a documentbuilder object, but newdocumentbuilder () is an abstract method and has not been implemented yet. Can it be called here? As you mentioned earlier, as long as an abstract class object can be generated, the abstract methods of this abstract class have been implemented? Is that true?
Newdocumentbuilder () Abstract METHODS will certainly be implemented by non-Abstract subclasses, which leads to polymorphism. During execution, the rewritten method of the subclass will be called.
Public class documentbuilderfactoryimpl extends documentbuilderfactory {
......................
}
Sun's newinstance () method
Public static documentbuilderfactory newinstance (){
Try {
Return (documentbuilderfactory) factoryfinder. Find (
/* The default property name according to the JAXP spec */
"Javax. xml. parsers. documentbuilderfactory ",
/* The fallback implementation class name */
"Com.sun.org. Apache. xerces. Internal. JAXP. documentbuilderfactoryimpl ");
} Catch (factoryfinder. configurationerror e ){
Throw new factoryconfigurationerror (E. getexception (),
E. getmessage ());
}
}
It should return a documentbuilderfactoryimpl instance with reflection, and then use documentbuilderfactory to perform forced conversion, that is, documentbuilderfactory. newinstance () returns an object-type documentbuilderfactory instance. You don't need to mention the following!
』
Import javax. xml. parsers. documentbuilder;
Import javax. xml. parsers. documentbuilderfactory;
Import java. Io. file;
Import org. W3C. Dom. Document;
Public class orderprocessor {
Public static void main (string ARGs []) {
File docfile = new file ("orders. xml ");
Document Doc = NULL;
Try {
Documentbuilderfactory DBF = documentbuilderfactory. newinstance ();
Documentbuilder DB = DBF. newdocumentbuilder ();
Doc = dB. parse (docfile );
} Catch (exception e ){
System. Out. Print ("problem parsing the file:" + E. getmessage ());
}
}
}
First, the Java code imports necessary classes and then it creates the orderprocessor application. The example in this tutorial only processes one file. Therefore, for the sake of conciseness, the application contains a direct reference to this file.
Therefore, the document object can be used later, and the application defines it outside the try-Catch Block.
In the try-Catch Block, the application creates documentbuilderfactory and then uses it to create documentbuilder. Finally, documentbuilder parses the file to create a document.
Parser settings
One of the advantages of using documentbuilder to create a parser is that it can control various settings on the parser created by documentbuilderfactory. For example, you can set the parser verification document:
Try {
Documentbuilderfactory DBF = documentbuilderfactory. newinstance ();
DBF. setvalidating (true );
Documentbuilder DB = DBF. newdocumentbuilder ();
Doc = dB. parse (docfile );
} Catch (exception e ){
...
Java Dom Level 2 allows you to control parser parameters using the following methods:
Setcoalescing (): determines whether the parser needs to convert the CDATA node to text, and whether to merge it with the surrounding text node (if applicable ). The default value is false.
Setexpandentityreferences (): determines whether to expand external entity references. If it is true, external data is inserted into the document. The default value is true. (See references for tips on using external entities .)
Setignoringcomments (): determines whether to ignore comments in the file. The default value is false.
Setignoringelementcontentwhitespace (): determines whether to ignore the white space in the element content (similar to the way the browser treats html ). The default value is false.
Setnamespaceaware (): determines whether the parser must pay attention to the namespace information. The default value is false.
Setvalidating (): by default, the parser does not validate the document. Set this parameter to true to enable the verification function.
W3C dom
The Document Object Model (DOM) is a platform-and language-independent interface that allows programs and scripts to dynamically access and update document content, structures, and styles. The document can be further processed, and the processing result can be stored back to the provided page.
Table 3-1 process Dom element attributes of an XML document
Attribute name
Description
Childnodes
Returns an array of all child elements of the current element.
Firstchild
Returns the first subelement of the current element.
Lastchild
Returns the last child element of the current element.
Nextsibling
Returns the elements that follow the current element.
Nodevalue
Specifies the read/write attribute of the element value.
Parentnode
Returns the parent node of an element.
Previussibling
Returns the element adjacent to the current element.
Table 3-2 Dom element methods used to traverse XML documents
Method Name
Description
Getelementbyid (ID) (document)
Obtain the elements in the document with the specified unique ID property value
Getelementsbytagname (name)
Returns an array of child elements with specified names in the current element.
Haschildnodes ()
Returns a Boolean value indicating whether the element has a child element.
Getattribute (name)
Returns the attribute value of an element. The attribute is specified by name.
Table 3-3 W3C Dom attributes and methods used for dynamic content creation
Attribute/Method
Description
Document. createelement (tagname)
The createelement method on the document object can create elements specified by tagname. If the DIV string is used as the method parameter, a div element is generated.
Document. createtextnode (text)
The createtextnode method of the Document Object creates a node that contains static text.
<Element>. appendchild (childnode)
The appendchild method adds the specified node to the list of child nodes of the current element. For example, you can add an option element as a subnode of the select element.
<Element>. getattribute (name)
These methods obtain and set the value of the name attribute in the element respectively.
<Element>. setattribute (name, value)
<Element>. insertbefore (newnode, targetnode)
This method inserts the node newnode as the child node of the current element in front of the targetnode element.
<Element>. removeattribute (name)
This method deletes the attribute name from the element.
<Element>. removechild (childnode)
This method deletes the child childnode from the element.
<Element>. replaceChild (newnode, oldnode)
This method replaces the node oldnode with the node newnode.
<Element>. haschildnodes ()
This method returns a Boolean value indicating whether the element has child elements.
Java and XML are a combination of gold. Many articles on the Internet have introduced that XML, as a data exchange in e-commerce, has become irreplaceable. However, during system development, we may not all use data exchange. Is it impossible to use XML?
Of course not. Now there is a new trend. The configuration files of Java programs start to use the XML format. In the past, they used the INI format similar to Windows. (Classes such as propertiesy are also used in Java to process such attribute configuration files ). Using XML as a Java configuration file has many advantages. From the tomcat installation configuration file and the J2EE configuration file, we have seen that XML is widely used, let's use XML to arm us with the trend.
Now the key is how to read the xml configuration file? There are several types of XML Parser: Mainly Dom and sax. These differences are described in many online articles.
In the XML project team of Apache, xerces xalan cocoon is currently used by several projects that develop XML-related technologies. Tomcat uses JAXP of sun, and xerces parser is used in its XSL taglib project.
Well, the above are all annoying theoretical issues. Please read the xml configuration file as soon as possible.
In our program, there are usually some variables determined according to the host environment. For example, the database access user name and password may be set differently on different hosts. You only need to change the xml configuration file to run properly. Localhost
Sqlname
Username
Password
The above myenv. xml configuration file is generally placed in the Tomcat WEB-INF/classes directory.
We compile a Java program to directly read and extract the dbhost dbuser dbpassword for other programs to access the database.
Currently, there are many methods of using sax. The main difference with Dom is that it reads XML files in a row for analysis. It is suitable for large files. Dom is a one-time read into the memory and obviously cannot deal with large files. here we use SAX parsing. Due to the continuous development of the SAX Parser, many articles on the Internet are aimed at the old version. if you use jdk1.4, you can refer to the article about processing XML documents with Sax. the program here is developed based on its improvements and has been debugged in practice ..
Import org. xml. Sax. attributes;
Import org. xml. Sax. helpers. defaulthandler;
Import org. xml. Sax. saxexception;
Import java. util. properties;
// The advantage of using defaulthandler is that you do not have to display all the methods,
Public class configparser extends defaulthandler {
/// Define a properties to store the value of dbhost dbuser dbpassword
Private Properties props;
Private string currentset;
Private string currentname;
Private stringbuffer currentvalue = new stringbuffer ();
// The Builder initializes props.
Public configparser (){
This. Props = new properties ();
}
Public properties getprops (){
Return this. Props;
}
// Define the method for starting element parsing. Here, the name xxx is extracted.
Public void startelement (string Uri, string localname, string QNAME, attributes)
Throws saxexception {
Currentvalue. Delete (0, currentvalue. Length ());
This. currentname = QNAME;
}
// Add the value to currentvalue
Public void characters (char [] CH, int start, int length) throws saxexception {
Currentvalue. append (CH, start, length );
}
// Save the previous names and values in props one by one after the end
Public void endelement (string Uri, string localname, string QNAME) throws saxexception {
Props. Put (QNAME. tolowercase (), currentvalue. tostring (). Trim ());
}
}
Is the above parsing procedure relatively simple? In fact, parsing XML is so simple.
Now we have extracted the value of dbhost dbuser dbpassword localhost sqlname Username Password, but this is only in the parser and our program cannot be accessed. We need to compile another program. Import java. util. properties;
Import javax. xml. parsers. saxparser;
Import javax. xml. parsers. saxparserfactory;
Import java.net. url;
Public class parsexml {
// Define a properties to store the value of dbhost dbuser dbpassword
Private Properties props;
// The props here
Public properties getprops (){
Return this. Props;
}
Public void parse (string filename) throws exception {
// Visualize our parser
Configparser handler = new configparser ();
// Obtain the sax factory object
Saxparserfactory factory = saxparserfactory. newinstance ();
Factory. setnamespaceaware (false );
Factory. setvalidating (false );
// Obtain the sax Parsing
Saxparser parser = factory. newsaxparser ();
// Get the configuration file myenv. xml directory. Tomcat is in WEB-INF/classes
// In the following example, beansconstants is a class used to store configuration information in XML files. You can replace or define it yourself.
URL confurl = beansconstants. Class. getclassloader (). getresource (filename );
Try
{
// Associate the parser with the parsing object myenv. XML to start parsing.
Parser. parse (confurl. tostring (), Handler );
// After obtaining the parsed attributes, other applications can extract the attribute names and values by calling the props of this program.
Props = handler. getprops ();
} Finally {
Factory = NULL;
Parser = NULL;
Handler = NULL;
}
}
}