XML programming (CRUD) _xml

Source: Internet
Author: User
Tags gettext object model xml parser xml reader

XML Programming (CRUD)

There are two ways to parse XML: DOM and sax

DOM: (Document Object model, which is the Documentation objects module) is a recommended way for the organization to work with XML.

Sax: (Simple API for XML) is not an official standard, but it is the de facto standard of the XML community, and almost all XML parsers support it.

XML Parser

Crimson, Xerces, Aelfred2

XML Parsing Development Package

Jaxp, Jdom, dom4j

The JAXP development package is part of the J2SE, consisting of Javax.xml, Org.w3c.dom, Org.xml.sax packages, and their child packages

In the Javax.xml.parsers package, several factory classes are defined, and programmers invoke these factory classes to get the parser objects of the DOM or SAX that parse the XML document.

The documentbuilderfactory in the Javax.xml.parsers package is used to create the parser object for the DOM schema, Documentbuilderfactory is an abstract factory class that cannot be instantiated directly, However, this class provides a Newinstance method that automatically creates an object for a factory and returns it based on the parser installed by default on the local platform.

Call the Documentbuilderfactory.newinstance () method to get the factory that created the DOM parser.

The Newdocumentbuilder method that invokes the factory object gets the DOM parser object.

Call the DOM parser object's parse () method to parse the XML document, get the Document object representing the entire file, and perform an operation on the entire XML document using the DOM attribute.

DOM Model (Document Object model)

When parsing an XML document, the DOM parser parses all the elements in the document into node objects (nodes) according to the hierarchical relationships it appears.

In the DOM, the relationships between nodes are as follows:

The node above one node is the parent of the node (parent)

A node under one node is a child node of that node (children)

At the same level, a node with the same parent node is a sibling node (sibling)

The node set at the next level of a node is a node descendant (descendant)

The parent, grandparent node, and all nodes above the node are the ancestors of the nodes (ancestor)

Node type

Node objects provide a series of Changshilai that represent nodes, and when a developer obtains a node type, it is possible to convert node nodes into corresponding node objects (node subclass objects) so that their unique methods can be invoked. (View API documentation)

The node object provides an appropriate way to obtain its parent node or child node. These methods allow programmers to read the contents of an entire XML document, or to add, modify, or delete the contents of an XML document.

DOM parsing programming

Traverse all nodes

Find a Node

Delete a node

Update nodes

Add node

The transformer class in the Javax.xml.transform package is used to convert the Document object representing the XML file to a format for output, such as converting an XML file to an HTML document when it is applied to a style sheet. With this object, you can, of course, write the document object back into an XML file.

The transformer class completes the conversion operation by means of a transform method that receives a source and a destination. We can pass:

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 destination of the data.

Transformer objects are obtained through transformerfactory.

When parsing an XML document using the DOM, you need to read the entire XML document, and in memory frame the Doucment object representing the entire DOM tree, and then manipulate the XML document. In this case, if the XML document is particularly large, it consumes a large amount of memory on the computer and can easily cause a memory overflow.

Sax parsing allows documents to be processed when they are read, without having to wait until the entire document is loaded before the document is operational.

Sax parses XML files using event handling, parsing XML documents with sax, involving two parts: parsers and event handlers:

The parser can be created using the JAXP API, and after creating the SAX parser, you can specify the parser to parse an XML document.

The parser uses Sax to parse an XML document, and as long as it resolves to an XML document, it invokes a method of the event handler that, when invoking the method of the event handler, passes the contents of the current parsed XML file to the event handler as a parameter to the method.

The event handler is written by the programmer, and the programmer can easily get the data parsed by the SAX parser through the parameters of the method in the event handler so that it can decide how to process the data.

Sax parsing

Read CONTENTHANDLERAPI documents, common methods: Startelement, endelement, characters

Using SAXParserFactory to create a sax parsing factory

SAXParserFactory SPF =saxparserfactory.newinstance ();

Get parser objects through sax parsing factory

SAXParser sp = Spf.newsaxparser ();

To get an XML reader through the parser object

XMLReader XMLReader = Sp.getxmlreader ();

Setting the event handler for the reader

Xmlreader.setcontenthandler (Newbookparserhandler ());

Parsing XML files

Xmlreader.parse ("Book.xml");

DOM4J is a simple, flexible library of open source code. DOM4J was developed by the early development of Jdom. Unlike Jdom, DOM4J uses interfaces and abstract people to separate and then separate base classes, although the DOM4J API is relatively complex, but it provides more flexibility than jdom.

DOM4J is a very good Java XML API with excellent performance, powerful features and easy to use. Now many software uses dom4j, such as Hibernate, including Sun's own JAXM also used dom4j.

With dom4j development, you need to download the appropriate jar file for dom4j.

In dom4j, there are three ways to obtain the Document object:

1. read XML file, get Document Object

Saxreader reader = Newsaxreader ();
Document document = Reader.read (new File ("Input.xml"));

2. Parse XML form text to get Document object.

String Text = "<members></members>";
Document document = Documenthelper.parsetext (text);

3. Actively create the Document object.

Document document = Documenthelper.createdocument ();
To create a root node

Element Root =document.addelement ("members");

1. Gets the root node of the document.

Element root = Document.getrootelement ();

2. Gets the child nodes of a node.

Elementelement=node.element ("title");

3. Get the text of the node

String Text=node.gettext ();

4. Get all the child nodes named "member" under a node and traverse it.
List nodes =rootelm.elements ("member");

for (Iterator it = Nodes.iterator (); It.hasnext ();) {
Element elm = (Element) It.next ();
Do something
}

5. Iterate over all child nodes under a node.
For (Iteratorit=root.elementiterator (); It.hasnext ();) {
Elementelement = (Element) it.next ();
Do something
}

6. Add child nodes under a node.
Element Ageelm = newmemberelm.addelement ("Age");

7. Set the node text.
Element.settext ("29");

8. Delete a node.
Childelm is the node to be deleted, Parentelm is its parent node

Parentelm.remove (Childelm);

9. Add a CDATA node.
Element Contentelm = infoelm.addelement ("content");
Contentelm.addcdata (Diary.getcontent ());

1. Get a property under a node
Elementroot=document.getrootelement ();
Properties Name Name

Attribute attribute=root.attribute ("size");

2. Get the text of the attribute
Stringtext=attribute.gettext ();

3. Delete a property
Attributeattribute=root.attribute ("size");
Root.remove (attribute);

3. Iterate through all the properties of a node
Elementroot=document.getrootelement ();
For (Iteratorit=root.attributeiterator (); It.hasnext ();) {
AttributeAttribute = (Attribute) it.next ();
Stringtext=attribute.gettext ();
System.out.println (text);
}

4. Set the properties and text of a node.
Newmemberelm.addattribute ("name", "sitinspring");

5. Set the text of the property
Attributeattribute=root.attribute ("name");
Attribute.settext ("sitinspring");

1. The document is all in English, do not set the encoding, directly written in the form.
XMLWriter writer = new XMLWriter (New FileWriter ("Output.xml"));
Writer.write (document);
Writer.close ();

2. The document contains Chinese, set the format of the encoding writing.
OutputFormat format = Outputformat.createprettyprint ();
Specify XML encoding

Format.setencoding ("GBK");
XMLWriter writer = new XMLWriter (Newfilewriter ("Output.xml"), format);
Writer.write (document);
Writer.close ();

1. The list of nodes where the insertion is to be inserted (list)

2. Call List.add (index,elemnent), which determines the insertion position of the element by index.

Element elements can be obtained by Documenthelper objects. Sample code:

Element AAA =documenthelper.createelement ("AAA");

Aaa.settext ("AAA");

List List = Root.element ("book"). elements ();

List.add (1, AAA);

Update document

1. Convert a string to XML

String Text = "<members><member>sitinspring</member></members>";
Document document = Documenthelper.parsetext (text);

2. Converts the XML of a document or node into a string.

Saxreader reader = new Saxreader ();
Document document = Reader.read (new File ("Input.xml"));
Element root=document.getrootelement ();


String Docxmltext=document.asxml ();

String Rootxmltext=root.asxml ();
Element memberelm=root.element ("member");
String Memberxmltext=memberelm.asxml ();

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.