Java Parsing xml

Source: Internet
Author: User

XMl (extensible Markup Language) Extensible Markup Language belongs to the data storage language
Features of XML:
Data can be read in any application
Extremely simple
Simplify data sharing and transfer
The difference between XML and HTML: HTML is designed to display information, while XML is designed to transmit information. XML requires that all tokens appear in pairs, are case-sensitive, and HTML tags are not case-sensitive.

(Dom parsing method)

Need to import Dom4j.jar package in Project
DOM4J is a Java XML API that is a jdom upgrade to read and write XML files. DOM4J is a very good javaxml API with excellent performance, powerful features and extremely easy to use features.
Link: https://pan.baidu.com/s/1c2pTmd6 Password: U6oy

Org.dom4j.io provides two classes: Saxreader and Domreader, which build a dom4j tree from an existing universe-wide DOM tree, while Saxreader uses a SAX parser to build dom4j trees from different input sources.

Saxreader Way:
Analytic Step-Outs:

1new  saxreader (); 2= reader.read (file file); the read () method can give a file path to the object 3) to get the root node  of the xml file =  Doc.getrootelement (); 4) Gets the elements under the node list<Element> childlist  =root.elements (); Gets the child element of the current element's specified name Root.element (String Name) gets the current element's Root.getname () gets the contents of the current element Root.gettext () Root.gettexttrim () Gets the content of the child elements of the specified name under the current element Root.elementtext (String Name) Gets the value of the current element Root.getstringvalue ();

The full code is as follows:

ImportJava.io.File;Importjava.util.List;Importorg.dom4j.Document;Importorg.dom4j.Element;ImportOrg.dom4j.io.SAXReader; Public classSaxreaderdemo { Public Static voidMain (string[] args) {Try {            //Create a Saxreader objectSaxreader reader =NewSaxreader (); //reading the XML file StructureDocument doc = Reader.read (NewFile ("Config/server.xml")); //gets the XML file root nodeElement root =doc.getrootelement (); //gets the child element of the root nodelist<element> list =root.elements ();  for(Element item:list) {if("MYSQL". Equals (Item.getname ())) {System.out.println ("MySQL Database"); //get sub-elements under MySQLList<element> List1 =item.elements (); //iterating over the element values of a child node                     for(Element element:list1) {System.out.println ("The current element is:" + element.getname () + "value is:" +Element.getstringvalue ()); }                } Else if("SQL Server". Equals (Item.getname ())) {System.out.println ("SQL Server Database"); //to get child elements under SQL ServerList<element> List1 =item.elements (); //iterating over the element values of a child node                     for(Element element:list1) {System.out.println ("The current element is:" + element.getname () + "value is:" +Element.getstringvalue ()); }                }            }        } Catch(Exception e) {e.printstacktrace (); }    }    }

My project structure is as follows:

The XML file is as follows:

<?xml Version = "1.0" encoding= "UTF-8"?><server>    <MySql>        <driver> Com.mysql.jdbc.driver</driver>        <url>jdbc:mysql://localhost:3306/database?usessl= true</url>        <user>root</user>        <pwd>1234</pwd>    </MySql>    <SQLServer>        <driver>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver>        <url>jdbc:sqlserver://localhost:1433;databasename=database</url>        < user>sa</user>        <pwd>1234</pwd>    </SQLServer></server>

Generating an XML file in Java

1the Document object is created by Documenthelper's CreateDocument () method to obtain the Document object (requires a guide package: Org.dom4j.document;o Rg.dom4j.DocumentHelper) Document Doc=documenthelper.createdocument ();2to create a root node note that the root node of the XML file can only have one (need to guide package: org.dom4j.Element) Element root=doc.addelement (String name);3adds a child node that returns the current node object element=root.addelement (String name);4You can continue adding nodes later, or you can add child nodes under Child.addelement (String name). Add node Child.addtext (String name); Add content in a node after you have perfected the DOM structure, you can write the document object to the XML file1) Create XmlWriter stream object XmlWriter writer=NewXMLWriter ();2) Set low-level output stream FileOutputStream fos for XmlWriter=NewFileOutputStream ("Config/new.xml"); Writer.setoutputstream (FOS);3writes the Document object to the XML file Writer.write (DOC);4) finally close the XmlWriter stream object Writer.close ();

The specific code is as follows:

Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;Importjava.io.UnsupportedEncodingException;Importorg.dom4j.Document;ImportOrg.dom4j.DocumentHelper;Importorg.dom4j.Element;ImportOrg.dom4j.io.XMLWriter; Public classCreatexml { Public Static voidMain (string[] args) {//Create Document ObjectDocument doc =documenthelper.createdocument (); //Creating the root nodeElement root = doc.addelement ("Server"); //Create two child nodes on the root nodeElement child1 = root.addelement ("MYSQL"); Element child2= Root.addelement ("SQL Server"); //Create a node under the first child nodeElement child1_driver = child1.addelement ("Driver"); Child1_driver.addtext ("Com.mysql.jdbc.Driver"); Element Child1_url= child1.addelement ("url"); Child1_url.addtext ("Jdbc:mysql://localhost:3306/database?usessl=true"); Element Child1_user= Child1.addelement ("User"); Child1_user.addtext ("Root"); Element child1_pwd= Child1.addelement ("pwd"); Child1_pwd.addtext ("1234"); //Create a node under the second child nodeElement child2_driver = child2.addelement ("Driver"); Child2_driver.addtext ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); Element Child2_url= child2.addelement ("url"); Child2_url.addtext ("Jdbc:sqlserver://localhost:1433;databasename=database"); Element Child2_user= Child2.addelement ("User"); Child2_user.addtext ("SA"); Element child2_pwd= Child2.addelement ("pwd"); Child2_pwd.addtext ("1234"); Try {            //creating a XmlWriter Stream objectXMLWriter writer=NewXMLWriter (); //Note: XMLWriter writer=new XMLWriter (outputstream os), can omit the second step//setting low-level output streams for XmlWriterFileOutputStream fos=NewFileOutputStream ("Config/new.xml");            Writer.setoutputstream (FOS); //writing the Document object to an XML fileWriter.write (DOC); //finally close the XmlWriter stream objectWriter.close (); } Catch(Exception e) {e.printstacktrace (); }     }}

After running the Code Refresh config found New.xml appeared ...

Java Parsing xml

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.