1. Create an XML file
Document Doc = new document (new element ("rootelement "))
Or
Document Doc = new document ();
// Root element
Element root = new element ("persons ");
Doc. addcontent (Root );
// Add person
Element person = new element ("person"). settext ("test1 ");
Root. addcontent (person );
// Add person 2
Person = new element ("person"). settext ("Test2 ");
Root. addcontent (person );
Another method:
Document Doc = new document (new element ("family ")
. Addcontent (new element ("mom "))
. Addcontent (new element ("dad"). addcontent ("kidofdad ")));
Ii. parsing XML files
Generally, org. JDOM. Input. saxbuilder is faster and is recommended. org. JDOM. Input. dombuilder is applicable to scenarios where DOM objects already exist.
Saxbuilder B = new saxbuilder ();
// Create the document
Document Doc = B. Build (new file (xmlfilename ));
- Get the root element: Element webapp = Doc. getrootelement ();
- Obtain sub-nodes (namespace supported ):
// Get a list of direct children as elements
List allchildren = element. getchildren ();
// Get all direct children with a given name
List namedchildren = element. getchildren ("name ");
// Get the first kid with a given name
Element KID = element.Getchild("Name ");
- Adding/deleting subnodes can operate on the subnode set like the list object. Of course, you can also operate on subnodes in the traditional way.
List allchildren = element. getchildren ();
// Remove the fourth child
Allchildren. Remove (3 );
// Remove all children named "Jack"
Allchildren. removeall (element. getchildren ("Jack "));
Or
Element. removechildren ("Jack ");
// Add a new child
Allchildren. Add (new element ("Jane "));
Or
Element. addcontent (new element ("Jane "));
// Add a new child in the second position
Allchildren. Add (1, new element ("second "));
// Read attributes:
String value = table. getattributevalue ("width"); // The table is an element.
// You can also convert the type while reading the attribute
Try {
Value = table. getattribute ("border"). getintvalue ();
}
Catch (dataconversionexception e ){}
// Set attributes
// Add an attribute
Table. addattribute ("vspace", "0 ");
// Add an attribute more formally
Table. addattribute (new attribute ("name", "value "))
// Remove an attribute
Table. removeattribute ("border ");
// Remove all attributes
Table. getattributes (). Clear ();
For example, <description> A cool demo </description>, you can directly obtain the content
String content = element. gettext ();
// Remove unnecessary white spaces. The white spaces before and after the string are not removed.
Element. gettextnormalize ();
// This blows away all current content
Element. settext ("a new description ");
// Special characters are interpreted correctly: special characters can be correctly converted
Element. settext ("<XML> content ");
// Create a CDATA Element
Element. addcontent (New CDATA ("<XML> content "));
Iii. Output XML
The xmloutputter class is used to output XML files. during creation, a format object is required to format XML files. The format object is a factory class, several static factory methods are provided to provide some common XML formats, such as getprettyformat ():
Xmloutputter outputter = new xmloutputter (format. getprettyformat ());
Try {
Outputter. Output (Doc, new fileoutputstream (new file ("xmlfile/persons. xml ")));
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
Iv. xml namespace support
Namespace XHTML = namespace. getnamespace ("XHTML", "http://www.w3.org/5o/xhtml ");
- The namespace object can be an optional parameter for most methods of element and attribute:
List kids = element. getchildren ("P", XHTML );
Element KID = element. getchild ("title", XHTML );
Attribute Height = element. getattribute ("height", XHTML );
Appendix: XML programming interface comparison in Java: Dom sax jdom jaxp (network loading)
I. Dom (Document Object Model)
Defines a set of interfaces for the parsed versions of the XML document. The parser reads the entire document, constructs a memory-resident tree structure, and then the code can use the DOM interface to operate on this tree structure.
Advantage: the entire document tree is in the memory for ease of operation. It supports multiple features such as deletion, modification, and rescheduling;
Disadvantages: transferring the entire document to memory (including useless nodes) wastes time and space;
Usage: once the document is parsed, the data needs to be accessed multiple times;
Sufficient hardware resources (memory and CPU)
Ii. Sax
To solve Dom problems, the following occurs.
Event-driven. When the parser finds the start, end, text, start, or end of an element, it sends events and programmers write code to respond to these events and save data.
Advantage: the entire document does not need to be transferred in advance, which consumes less resources;
The code of the SAX Parser is smaller than that of the DOM parser. It is suitable for Applet and download.
Disadvantage: it is not persistent. After an event, if no data is saved, the data will be lost;
Stateless; only the text can be obtained from the event, but I do not know which element the text belongs;
Usage: applet;
Only a small amount of content in the XML document is required, and few requests are returned;
Low machine memory;
Iii. JDOM
To reduce the Dom and sax encoding volumes, JDOM appears;
Advantage: The 20-80 principle greatly reduces the amount of code
Application scenarios: The functions to be implemented are simple, such as parsing and creation. However, at the underlying layer, JDOM still uses SAX (most commonly used), Dom, and xanan
Iv. Japan
Provides unified programming interfaces for multiple XML Parser
Change the parser without changing the code
Usage: If JDOM is not used, it is generally recommended to use japx to isolate the code from the implementation details of various Resolvers.
This article from: http://www.blogjava.net/cherishchen/archive/2007/07/04/128138.html