XML operations in Java

Source: Internet
Author: User

I. Introduction to XML

XML is an Extensible Markup language that is used primarily to tag data, define data types, and is ideal for world Wide Web transport.

XML Features:

    1. XML is a markup language, much like HTML
    2. XML is designed to transmit data instead of displaying data
    3. The XML tag is not predefined and you need to define your own label
    4. XML is designed to be self-descriptive
    5. XML is the recommended standard for the consortium
XML vs. html:
    • XML is designed to transmit and store data, with the focus on the content of the data.
    • HTML is designed to display data with the focus on the appearance of the data.
    • HTML is designed to display information, while XML is designed to transmit information.
Example:
<bookstore>    <book category= "Children" >         <title>harry potter</title>         < Author>jk. rowing</author>         <year>2005</year>         <price>35.2</price>    </book ></bookstore>
Elements can contain other elements, text, or mixtures of both. Elements can also have properties.<bookstore> and <book> have element content,<author> only text content,<book> also have attributes.
second, Dom way to read XML
Create a new Java project and place a languages.xml in the project root directory:
<?xml version= "1.0" encoding= "UTF-8"? ><languages cat= "It" >   <lan id= "1" >      <name>java </name>      <ide>Eclipse</ide>   </lan>   <lan id= "2" >      <name> swift</name>      <ide>Xcode</ide>   </lan>   <lan id= "3" >      <name >C#</name>      <ide>visual studio</ide>   </lan></Languages>
Dom way to read XML files:
Import Java.io.file;import java.io.ioexception;import java.util.iterator;import javax.xml.parsers.DocumentBuilder; Import Javax.xml.parsers.documentbuilderfactory;import Javax.xml.parsers.parserconfigurationexception;import Org.w3c.dom.document;import Org.w3c.dom.element;import Org.w3c.dom.node;import Org.w3c.dom.NodeList;import Org.xml.sax.saxexception;public class ReadXml {public static void main (string[] args) {try {// Dom Mode Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();D Ocumentbuilder builder = Factory.newdocumentbuilder ();D ocument Document = builder.parse (New File ("Language.xml")); Element root = Document.getdocumentelement (); System.out.println ("cat=" + Root.getattribute ("cat")); NodeList list = Root.getelementsbytagname ("LAN"); for (int i = 0; i < list.getlength (); i++) {Element lan = (Element) Li St.item (i); System.out.println ("------------------"); System.out.println ("id=" + lan.getattribute ("id"));/* * Element name= (Element) * Lan.getelementsbytagname ("name")). Item (0); * SYSTEM.OUT.PRINTLN ("name=" +name.gettextcontent ()); Element * Ide= (Element) lan.getelementsbytagname ("IDE"). Item (0); * SYSTEM.OUT.PRINTLN ("ide=" +ide.gettextcontent ()); */nodelist clist = Lan.getchildnodes (); for (int j = 0; J < Clist.getlength (); j + +) {Node c = Clist.item (j); if (c Instan Ceof Element) {System.out.println (C.getnodename () + "=" + c.gettextcontent ());}}} catch (Parserconfigurationexception e) {e.printstacktrace ();} catch (Saxexception e) {e.printstacktrace ();} catch ( IOException e) {e.printstacktrace ();}}}

Output:
Cat=it------------------id=1name=javaide=eclipse------------------id=2name=swiftide=xcode------------------id= 3name=c#ide=visual Studio

third, Dom way to create XML

Package Ucas.yp.xml;import Java.io.file;import Java.io.stringwriter;import javax.xml.parsers.DocumentBuilder; Import Javax.xml.parsers.documentbuilderfactory;import Javax.xml.parsers.parserconfigurationexception;import Javax.xml.transform.result;import Javax.xml.transform.transformer;import Javax.xml.transform.transformerconfigurationexception;import Javax.xml.transform.transformerexception;import Javax.xml.transform.transformerfactory;import Javax.xml.transform.dom.domsource;import Javax.xml.transform.stream.streamresult;import Org.w3c.dom.document;import Org.w3c.dom.element;public Class createxml {public static void main (string[] args) {try {documentbuilderfactory factory= Documentbuilderfactory.newinstance ();D Ocumentbuilder builder = factory.newdocumentbuilder ();D ocument document= Builder.newdocument (); Element root=document.createelement ("Languages"); Root.setattribute ("Cat", "it"); Element lan1=document.createelement ("LAN"); Lan1.setattribute ("id", "1"); Element Name1=document.createelemeNT ("name"); Name1.settextcontent ("Java"); Element ide1=document.createelement ("IDE"); Ide1.settextcontent ("Eclipse"); Lan1.appendchild (name1); Lan1.appendchild (IDE1);//from inside to outside layer packing element lan2=document.createelement ("LAN"); Lan2.setattribute ("id", "2"); Element name2=document.createelement ("name"); Name2.settextcontent ("Swift"); Element ide2=document.createelement ("IDE"); Ide2.settextcontent ("Xcode"); Lan2.appendchild (name2); Lan2.appendchild (IDE2); Element lan3=document.createelement ("LAN"); Lan3.setattribute ("id", "3"); Element name3=document.createelement ("name"); Name3.settextcontent ("C #"); Element ide3=document.createelement ("IDE"); Ide3.settextcontent ("Visual Studio"); Lan3.appendchild (Name3);    Lan3.appendchild (IDE3); Root.appendchild (lan1); Root.appendchild (lan2); Root.appendchild (LAN3);    Document.appendchild (root);    Transformerfactory trfactory=transformerfactory.newinstance ();    Transformer Transformer=trfactory.newtransformer ();    StringWriter writer=new StringWriter (); Transformer.transform (nEW Domsource (document), new Streamresult (writer));//-----string Output System.out.println (writer.tostring ());//----- Generate XML file Transformer.transform (new Domsource (document), New Streamresult (New File ("Newxml.xml"));} catch (Parserconfigurationexception e) {e.printstacktrace ();} catch (Transformerconfigurationexception e) { E.printstacktrace ();} catch (Transformerexception e) {e.printstacktrace ();}}}

Iv. manipulating XML using DOM4J
dom4j is a good library of Java operations XML,Features excellent performance, powerful features and extremely easy to use. : HTTP://WWW.DOM4J.ORG/DOM4J-1.6.1/
Package Ucas.yp.xml;import Java.io.filewriter;import Java.io.ioexception;import org.dom4j.document;import Org.dom4j.documentexception;import Org.dom4j.documenthelper;import Org.dom4j.io.xmlwriter;public class TestDom4j { public static void Main (string[] args) {String xmlstring = "<bookstore><book><title>harry potter</ Title><author>jk. Rowing</author><year>2005</year><price>35.2</price></book></bookstore > "; try {document document = Documenthelper.parsetext (xmlstring);//Print System.out.println (Document.asxml ());// Generate XML file XMLWriter writer = new XMLWriter (New FileWriter ("Book.xml")); Writer.write (document); Writer.close ();} catch (Documentexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}}
Refresh the project catalog to see the newly generated book.xml.



XML operations in Java

Related Article

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.