Parsing XML files Java-web Dom Way

Source: Internet
Author: User
Tags xml attribute

XML DOM tree structure:

DOM node

Each component in the Dom,xml document is a node .

This is what the DOM provides:

    • The entire document is a document node
    • Each XML element is an element node
    • The text contained in the XML element is a text node
    • Each XML attribute is an attribute node
    • Comment is a comment node
Common node types
Node type NodeType Named Constant return value of NodeName return value of NodeValue
Element 1 Element_node Element name Null
Attr 2 Attribute_node Property name Property value
Text 3 Text_node #text Node name

Case:

Target: After parsing the XML file, the Java program can get all the data of the XML file

Thinking: How to preserve the structure information of XML after parsing

XML document:

Instance:

 PackageTest;/*** Case: Use DOM to parse XML file to get all the data of XML file*/ImportJavax.xml.parsers.DocumentBuilder;Importjavax.xml.parsers.DocumentBuilderFactory;Importorg.w3c.dom.Document;Importorg.w3c.dom.Element;ImportOrg.w3c.dom.NamedNodeMap;ImportOrg.w3c.dom.Node;Importorg.w3c.dom.NodeList; Public classDomdemo { Public Static voidMain (string[] args)throwsException {/**Step One: Create an Documentbuilderfactory Object * 1. Define the factory API, which enables applications to get the parser that generates the DOM object tree from an XML document. * 2. protected Documentbuilderfactory () * is used to block the instantiated protected construction method * 3.         Static Documentbuilderfactory newinstance () * Gets a new instance of Documentbuilderfactory. */documentbuilderfactory dbf=documentbuilderfactory.newinstance (); /**Step Two: Create a Documentbuilder Object * 1.protected documentbuilder () * Protected construction method * 2. Get the DOM document instance from the XML document.         With this class, the application programmer can get a Document from XML. */Documentbuilder DB=Dbf.newdocumentbuilder (); /**Step three: Load the Book.xml file into the current directory by using the parse method of the Documentbuilder object * 1.parse (file f) * resolves the contents of the given file to an XML document and returns a         The new DOM Document object. */Document Document= Db.parse ("books.xml"); /**Step four: Get a collection of all book Nodes * 1.getElementsByTagName (): Get all nodes with the same name through the names of the nodes, * because there is not only one node, so all the acquired nodes are stored in a node collection         。 */NodeList Booklist= document.getElementsByTagName ("book"); System.out.println ("A total" + booklist.getlength () + "book"); /**Step five: Traverse each book node * 1.Node item (int index) * Returns the index item in the collection.         * 2.NamedNodeMap getattributes () * Contains the NamedNodeMap of the property of this node (if it is Element); otherwise null. */                 for(inti = 0; I < booklist.getlength (); i++){                        //premise: Do not know how many ID attributes of the book nodeSystem.out.println ("===========" below begins to traverse the "+ (i+1) +" contents of this book =========== "); //get a book node with the Item methodNode book =Booklist.item (i); //gets all the property collections of the book NodeNamedNodeMap attrs =book.getattributes (); System.out.println ("First" + (i+1) + "book Total" + attrs.getlength () + "Properties"); //traversing the properties of a book             for(intj = 0; J < Attrs.getlength (); J + +){                //get a property of a book node by the Item methodNode attr =Attrs.item (j); //Get Property nameSystem.out.print ("Property name:" +attr.getnodename ()); //Get Property valueSystem.out.println ("--Attribute value:" +Attr.getnodevalue ()); }                        /*//premise: Already known that the book node has only one ID attribute//The book node is coerced type conversion to element type element ebook = (Element)            Booklist.item (i);            Get the property value by GetAttribute ("id") method String AttrValue = Ebook.getattribute ("id"); SYSTEM.OUT.PRINTLN ("id attribute value:" + attrValue);*/                        /**Step Six: Parse the child nodes of the book node * 1.NodeList getchildnodes () * contains NodeList for all child nodes of this node. */NodeList childNodes=book.getchildnodes (); //Traverse childnodes to get the node name and node value for each nodeSystem.out.println ("i+1" + "book Total" + childnodes.getlength () + "Child Node");  for(intk = 0; K < Childnodes.getlength (); k++){                                /*If the node type is not judged * traversing the child node of the book node will find 9 child nodes, but we have only written 4 child nodes * Output 5 #text nodes, this is the text type of node.                 * Because the space is also a child node, I will also be traversed out. * */                //distinguishes between node of type text and element type.                if(Childnodes.item (k). Getnodetype () = =Node.element_node) {                    //Gets the node name of the element type nodeSystem.out.print ("s" + (k+1) + "node is" + Childnodes.item (k). Getnodename () + ":"); /*when we use Childnodes.item (k). Getnodevalue () This method gets the node value of the node of type * element, which is returned empty, because he thinks * & Lt;name> Ice and Fire song </name> "Song of Ice and Fire" is a sub-node of <name>, so the value of the return <name> node is of course null, because it thinks that "Song of Ice and Fire" is a node and                     Not content.                     * We need to return the first child node of the <name> node, then return the value of the first child node, * or with gettextcontent () can also be resolved, it will get all the child nodes of the node value * */                    //System.out.println (Childnodes.item (k). Getfirstchild (). Getnodevalue ());System.out.println (Childnodes.item (k). Gettextcontent ()); }                        }                    }        }}

Operation Result:

There are 2 books , ===========. The following begins to traverse the contents of the 1th book =========== 1th book has 1 Properties property name: ID--property value:1 89==== ======= below begins to traverse the 2nd book's contents =========== 2nd book A total of 1 Property property name: ID--attribute value:22004 The 8th node is language: 中文版

Parsing XML files Java-web Dom Way

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.