XML authentication tutorial, Part 1: Dom parser

Source: Internet
Author: User


XML authentication tutorial, Part 1: Dom parser




Content:
Dom Basics
Basic Dom node types
Three-step document parsing process
Basic Applications
Common Dom Methods
Edit document


In the XML & web services area, there are:
Teaching
Tools and products
All articles



Dom Basics

Before getting started with Dom, understand what it actually represents. Dom document is a collection of nodes or information fragments organized by hierarchies. This hierarchy allows developers to browse the tree to find specific information. Generally, the analysis structure needs to load the entire document and the hierarchy before completing any work.

Because Dom is based on information hierarchies, it is called tree-based.

For extremely large documents, loading the entire document and parsing the document will be slow and take up a lot of resources, so you need to process the data in other ways. Some event-based models, such as simple API for XML (SAX), work on data streams and process them when data streams pass through. The event-based API eliminates the need to build a data tree in the memory, but it does not allow developers to actually change the data in the original document.

On the other hand, Dom also provides an API that allows developers to create applicationsProgramAdd, edit, move, or remove nodes anywhere in the tree.

Basic Dom node types

The most common node types in XML:

    1. Node: Basic DOM data type.
    2. Element: the most important object to be processed is element.
    3. ATTR: the attribute of an element.
    4. Text: the actual content of an element or ATTR.
    5. Document: represents the entire XML document. A document object is also called a DOM tree.

Uncommon node types: CDATA, comments, processing instructions, and document snippets:

    • CDATA: abbreviation of "character data"
    • NOTE: Annotations contain information about data, which is usually ignored by applications.
    • Processing Command: PI is information specific to applications.
    • Document snippets: to form a good format, a document can have only one root element. Sometimes, you must create several sets of elements temporarily, which are not necessary to meet your needs.

The document snippets are similar to the following:

<Item instock = "Y" Itemid = "sa15"> <Name> Silver show saddle, 16. Inch </Name> <price> 825.00 </price> <qty> 1 </qty> </item> <item instock = "N" Itemid = "c49"> <name> premium cinch </Name> <price> 49.00 </price> <qty> 1 </qty> </item>

Three-step document parsing process

To use information in an XML file, you must parse the file to create a document object.

The document object is an interface, so it cannot be directly instantiated; on the contrary, applications generally use factory. The exact process varies with the implementation, but the idea is the same. In the sample JAXP environment, File Parsing is a three-step process:

    1. Create documentbuilderfactory. This object will create documentbuilder.
    2. Create documentbuilder. Documentbuilder parses the file to create a document object.
    3. Parse the file to create a document object.

If necessary, do not changeCodeJAXP allows different parsers. Let's continue and start building the application.

Basic Applications

Create an application named orderprocessor.

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. ");}}}

First, import necessary classes in Java, and then create the orderprocessor application. This example in this tutorial will only process one file, so for the sake of simplicity, this application contains a direct reference to it.

The application defines a Document Object outside the try-Catch Block so that this object can be used later. Try-catch enables you to execute operations that may throw exceptions, so that the entire application is not compromised. If an exception is thrown, the application simply executes the catch code.

In the try-Catch Block, the application creates documentbuilderfactory and uses it to create documentbuilder. Finally, documentbuilder parses the file to create a document.

Common Dom Methods

    1. Document. getdocumentelement ()
      Returns the root element of the document.
    2. Node. getfirstchild () and node. getlastchild ()
      Returns the first child of a given node.
    3. Node. getnextsibling () and node. getpreviussibling ()
      These methods return the compatriot of the next or previous given node.
    4. Node. getattribute (attrname)
      For a given node, the attribute of the given name is returned. For example, if you want to obtain an object named ID, you can call getattribute ("ID ").

Edit document

  1. Change node data
    Node. setnodevalue (elemvalue );
  2. Add Node
    String totalstring = new double (total ). tostring (); node totalnode = Doc. createtextnode (totalstring); // create a new text node for the document object. This node has totalstring element totalelement = Doc. createelement ("Total"); // create the new element total totalelement. appendchild (totalnode); // Add the node to the new total element. Thisorder. insertbefore (totalelement, thisorder. getfirstchild (); // Add the new element to the document, specify the new node, and specify the new node before the node
  3. Remove nodes
    Node deadnode = thisorderitem. getparentnode (). removechild (thisorderitem );
  4. Replace Node
    Element backelement = Doc. createelement ("backordered"); // create a new element backordered node deadnode = thisorderitem. getparentnode (). replaceChild (backelement, thisorderitem );
  5. Create and set attributes
    Element backelement = Doc. createelement ("backordered"); // create a new backordered backelement. setattributenode (Doc. createattribute ("Itemid"); // create a new property, Itemid string itemidstring = thisorderitem. getattributenode ("Itemid "). getnodevalue (); // obtain the value backelement of the Itemid attribute of thisorderitem. setattribute ("Itemid", itemidstring); // You can omit createattribute node deadnode = thisorderitem to set the value of the backelement attribute item. getparentnode (). replaceChild (backelement, thisorderitem );
  6. Remove attributes
    Element thisorder = (element) orders. item (ordernum); element customer = (element) thisorder. getelementsbytagname ("cusomertid "). item (0); customer. removeattribute ("Limit"); // remove the property limit

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.