parsing XML files using the DOM in Java

Source: Internet
Author: User

XML is a convenient and efficient format for data preservation and transmission, and XML is the primary way to transfer traffic between servers and clients before JSON is widely used. Therefore, it is necessary to use various methods to parse the information sent by the server for the user to view.

Java as a high-level language, with a variety of methods to parse XML files, such as DOM, SAX, and dom4j and other frameworks are available, this article uses a specific example, a simple introduction of the DOM to parse an XML file process.

Dom parsing is based on the document format, which we also meet in the foreground programming, which is the "Document Object Model", which we consider as an inverted tree structure, based on which to parse the document.

The example above provides an XML file that contains information about two books that we need to parse out and convert to the corresponding Java instance Object!

<?XML version= "1.0" encoding= "UTF-8"?><Root>    < Book>        <name>The man who stole the shadow</name>        <author>Markrivi</author>        < Year>2010</ Year>    </ Book>    < Book>        <name>There is no limit to life</name>        <author>Nick Vujicic</author>        < Year>2010</ Year>    </ Book></Root>

We can see that each book contains three attributes, then the corresponding parsing code is:

 PackageCom.minlz.xml;ImportJava.lang.reflect.Field;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;ImportJavax.xml.parsers.DocumentBuilder;Importjavax.xml.parsers.DocumentBuilderFactory;Importorg.w3c.dom.Document;ImportOrg.w3c.dom.Node;Importorg.w3c.dom.NodeList;/** * @authorMinliangzhi * @date September 7, 2016*/ Public classDomparser { Public Static voidMain (string[] args) {/*** General steps for DOM Parsing xml: Factory mode * 1, building a constructor factory * 2, building a constructor * 3, parsing an XML file with a constructor*/Documentbuilderfactory Factory=documentbuilderfactory.newinstance (); Documentbuilder Builder=NULL; Document Document=NULL; Try{Builder=Factory.newdocumentbuilder (); Document= Builder.parse ("Resources/books.xml"); } Catch(Exception e) {e.printstacktrace (); } List<Book> Allbook =NewArraylist<book>(); if(Document! =NULL) {            /**Gets the data root node of the XML file information*/NodeList Books= document.getElementsByTagName ("book"); intBookcount =books.getlength ();  for(inti = 0; i < Bookcount; i++) {                /**traverse each data record*/Map<string, object> att =NewHashmap<string, object>(); NodeList Properties=Books.item (i). Getchildnodes (); intProcount =properties.getlength ();  for(intj = 0; J < Procount; J + +) {                    /**traverse all properties of each data record*/                    /**Note that the Procount here is a total of 7 because it includes the empty part between the nodes and the nodes, but actually we are dealing with Element_node*/node Node=Properties.item (j); if(Node.getnodetype () = =Node.element_node)                    {Att.put (Node.getnodename (), Node.getfirstchild (). Getnodevalue ()); }}= Buildobject (book.class, ATT);            Allbook.add (book); }             for(book B:allbook) {System.out.println (b.tostring ()); }        }    }        Private Static<T> T buildobject (class<t> clazz, map<string, object>attributes) {T T=NULL; Try {            /**Initializes an instance of*/T=clazz.newinstance (); Field[] AllFields=Clazz.getdeclaredfields (); /**iterates through all properties and sets the value if the value of the property has been provided*/             for(Field f:allfields) {if(Attributes.containskey (F.getname ())) {f.setaccessible (true);                F.set (t, Attributes.get (F.getname ())); }            }        } Catch(Exception e) {e.printstacktrace (); }                 returnT; }}classBook {PrivateString name; PrivateString author; PrivateString Year;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getauthor () {returnauthor; }     Public voidSetauthor (String author) { This. Author =author; }     PublicString getYear () {returnYear ; }     Public voidSetyear (String year) { This. Year =Year ; } @Override PublicString toString () {return"Book [name=] + name +", author= "+ author +", year= "+ Year+ "]"; }}

Familiar with the HTML or JS friends may easily see the middle parsing of that part of the logic, the specific DOM structure there are many kinds and attributes, in this does not introduce, as long as the familiar with the process and mode, more than read the document more memory will slowly familiar, do not have to recite all the rules, use is the most important.

In the code, there is a method called "Buildobject", where reflection knowledge is used to build an instance based on the provided set of attributes, and unfamiliar to look at the reflection-related knowledge.

At last:

If there is any mistake, please correct me, I appreciate it!

parsing XML files using the DOM in Java

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.