* Java operations on XML files

Source: Internet
Author: User

there are four methods to read XML files in the Java environment: Dom, sax, JDOM, and jaxb
1. dom (Document Object Model)
This method is mainly provided by W3C. It reads all XML files into the memory and then forms a data tree with each element, to quickly access each node. Therefore, it consumes a lot of system performance and is not suitable for parsing large documents using the DOM method. Dom APIs directly follow the XML specification. Each node can be extended based on the node interface. In the perspective of polymorphism, it is excellent, but the application in Java is inconvenient and the readability is not strong.
instance:
Import javax. XML. parsers. *;
// XML Parser interface
Import Org. w3C. dom. *;
// Dom Implementation of XML
Import Org. apache. crimson. tree. xmldocument;
// used to write an XML file

Documentbuilderfactory factory = documentbuilderfactory. newinstance ();
// Allowed namespace
Factory. setnamespaceaware (true );
// Allow verification
Factory. setvalidating (true );
// Obtain an instance of documentbuilder
Try {
Documentbuilder builder = factory. newdocumentbuilder ();
} Catch (parserconfigurationexception PCE ){
System. Err. println (PCE );
// Output the exception information when an exception occurs, and then exit, the same below
System. Exit (1 );
}
// Parse the document and obtain an example of the document.
Try {
Document Doc = builder. parse (fileuri );
} Catch (domexception DOM ){
System. Err. println (DOM. getmessage ());
System. Exit (1 );
} Catch (ioexception IOE ){
System. Err. println (IOE );
System. Exit (1 );
}

// Obtain the root node stuinfo
Element elmtstuinfo = Doc. getdocumentelement ();

// Get all student nodes
Nodelist nlstudent = elmtstuinfo. getelementsbytagnamens (
Strnamespace, "student ");
For (......) {
// Current student node Element
Element elmtstudent = (element) nlstudent. item (I );

Nodelist nlcurrent = elmtstudent. getelementsbytagnamens (
Strnamespace, "name ");
}

The method for reading and obtaining data is actually very simple, and writing data into XML files is also not complicated.

Documentbuilderfactory factory = documentbuilderfactory. newinstance ();
Documentbuilder builder = NULL;
Try {
Builder = factory. newdocumentbuilder ();
} Catch (parserconfigurationexception PCE ){
System. Err. println (PCE );
System. Exit (1 );
}

Document Doc = NULL;
Doc = builder. newdocument ();

// The following is the process of creating the XML document content,
// First establish the root element "student roster"
Element root = Doc. createelement ("student roster ");
// Add the document to the root element
Doc. appendchild (Root );
// Create a "student" element and add it to the root element
Element student = Doc. createelement ("student ");
Student. setattribute ("gender", studentbean. getsex ());
Root. appendchild (student );
// Create a "name" element and add it to the student, the same below
Element name = Doc. createelement ("name ");
Student. appendchild (name );
Text tname = Doc. createtextnode (studentbean. getname ());
Name. appendchild (tname );

Element age = Doc. createelement ("Age ");
Student. appendchild (AGE );
Text Tage = Doc. createtextnode (string. valueof (studentbean. getage ()));
Age. appendchild (Tage );

2. Sax (Simple API for XML)
This method is mainly developed by members of the XML-DEV mail list, And sax is an event-based method, which is similar to the processing mechanism of the tag library, call the corresponding interface implementation method at the beginning, end, and error occurrence of the tag. Not all documents are read into the memory. Sax has excellent performance and uses less storage space. The Design of sax only considers the power of functions, but does not considerProgramWhether it is convenient to use.

Contenthandler, errorhandler, and dtdhandler must be extended, but contenthandler (or defaulthandler) must be extended ).

Import org. xml. Sax .*;

Public class mycontenthandler implements contenthandler {
... ...
}

/**
* When another call event occurs, call this method to locate it in the document.
* @ Param Locator
*/
Public void setdocumentlocator (locator Locator ){

}
/**
* Called at the beginning of parsing the entire document
* @ Throws saxexception
*/
Public void startdocument () throws saxexception {
System. Out. println ("** student information start **");
}
/**
* Called at the end of parsing the entire document
* @ Throws saxexception
*/
Public void enddocument () throws saxexception {
System. Out. println ("***** student information end ****");
}

/**
* Called at the beginning of namespace resolution
* @ Param prefix
* @ Param URI
* @ Throws saxexception
*/
Public void startprefixmapping (string prefix
, String URI) throws saxexception {
}
/**
* Called at the end of namespace resolution
* @ Param prefix
* @ Throws saxexception
*/
Public void endprefixmapping (string prefix) throws saxexception {
}
/**
* Called at the beginning of parsing an element
* @ Param namespaceuri
* @ Param localname
* @ Param QNAME
* @ Param ATTS
* @ Throws saxexception
*/
Public void startelement (string namespaceuri, string localname
, String QNAME, attributes ATTS) throws saxexception {
}
/** Called when the parsing element ends
* @ Param namespaceuri
* @ Param localname local place name, such as student
* @ Param QNAME: original name, for example, student: Student
* @ Throws saxexception */
Public void endelement (string namespaceuri, string localname, string QNAME) throws saxexception {
If (localname. Equals ("Student ")){
System. Out. println (localname + ":" + currentdata );
}
}
Method for Retrieving Element Data-characters
Method for getting blank content in element data-ignorablewhitespace
The method called when parsing to processing commands -- processinginstruction
Method called when the unverified parser ignores an object -- skippedentity
When running, you only need to use the following Code :

Mysaxparser = new mysaxparser ();

Mysaxparser. parserxmlfile ("sutinfo. xml ");

3. JDOM

The JDOM processing method is similar to Dom, but it is mainly implemented using sax. JDOM uses Java data types to define nodes of the operation data tree. JDOM has excellent performance.

Import org. JDOM .*;
Import org. JDOM. Input .*;
Import org. JDOM. Output .*;

Saxbuilder builder = new saxbuilder (false );
// Obtain the document
Document Doc = builder. Build (fileuri );
// Namespace
Namespace NS = namespace. getnamespace ("namespaces"
, "Http://www.lit.edu.cn/student ");

// obtain the set of all student nodes.
List lststudents = elmtstuinfo. getchildren ("student", NS);

For (... ){
Element elmtstudent = (element) lststudents. Get (I );
Elmtstudent. getchildtexttrim ("name", NS );
}
// Modify
Elmtlesson. getchild ("lessonscore", NS). settext ("100 ");
// Delete
Elmtstuinfo. removechild ("master", NS );
// Add
Elmtstuinfo. addcontent (new element ("master", NS). addcontent (New Entity ("mastername ")));
// Output document
// The first parameter is the indent string, which contains four spaces.
// The second parameter is true, indicating that a line break is required.
Xmloutputter printdoc = new xmloutputter ("", true );
Printdoc. Output (Doc, new fileoutputstream ("stuinfo. xml "));

4. jaxb (Java and XML binding)

Jaxb was published by sun-based companies. Jaxb maps Schema (or DTD) to a Java object (. Java file) and uses these Java objects to parse XML files. You must generate a Java file before using it. Therefore, you must have a fixed schema and cannot process dynamic XML files.

First, use the xjc command to generate a Java file.
Xjc [-options...]

(Many files are generated)
Jaxbcontext JC = jaxbcontext. newinstance ("packagename ");

Unmarshaller = JC. createunmarshaller ();

Collection collection = (Collection) unmarshaller. unmarshal (new file ("books. xml "));
Collectiontype. bookstype = collection. getbooks ();
List booklist = bookstype. getbook ();
For (... ){
Test. jaxb. booktype book = (test. jaxb. booktype) Booklist. Get (I );
System. Out. println ("book name:" + book. getname (). Trim ());
System. Out. println ("book ISBN:" + book. getisbn ());
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.