How to parse XML using Jdom in Javaweb _java

Source: Internet
Author: User

First, the preface

What is Jdom?

Jdom is an open source project that uses pure Java technology to parse, generate, serialize, and manipulate XML documents based on a tree-shaped structure. It is directly for Java programming services, using the features of the Java language (method overload, collection), combining the functionality of Sax and DOM, as much as possible to the original parsing XML, we use Jdom parsing XML will be an easy thing.

Advantages of Jdom:

1. Jdom is dedicated to Java technology and consumes less memory than DOM applications.

2. Jdom provides a simpler and more logical way to access XML information

3. In addition to XML files, Jdom can also access other data sources, such as creating classes to access data from SQL query results

The composition of the Jdom:

Jdom is composed of 6 packages

An element class represents the elements of an XML document

Org.jdom: Parsing the base class to use for XML files

Org.jdom.adapters: Java class with Dom fit

Org.jdom.filter: Filtering classes that contain XML documents

Org.jdom.input: Contains Java classes that read XML documents

Org.jdom.output: Classes that contain output XML documents

Org.jdom.trans form: Contains Java classes that convert jdom XML document interfaces to other XML document interfaces

What is XML?

XML is a widely used extensible markup language, there are many ways to parse XML in Java, most commonly used like Jdom, dom4j, sax, and so on.

Jdom Package Download: http://www.jdom.org/downloads/index.html

The author's code here is to use Java to create an XML and read an XML, only as a note introduction.

Second, the operation

Download the Jdom package, extract the file Jdom-2.0.6.jar,jdom-2.0.6-javadoc.jar, and import the package into the Lib folder. (Note, if there is a mistake, all the packages in Jdom are imported)

Example 1: Use Jdom to create an XML file with the name People.xml

New Class Careatejdom

Package com.book.jdom;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import org.jdom2.Document;
Import org.jdom2.Element;
Import Org.jdom2.output.Format;
Import Org.jdom2.output.XMLOutputter; Generate an XML file public class Createjdom {public static void main (string[] args) {//define elements element people,student; people = new E
Lement ("people");
Student = new Element ("Student");
Sets the property Student.setattribute ("name", "John");
Student.setattribute ("Salary", "8000");
Set the text Student.settext ("hehe");
Add it to the root directory people.addcontent (student);
Create a new document.
Document doc = new document (people);
Reads the format, assigns values to the current format format of format = Format.getcompactformat ();
Initializes the current format format.setencoding ("UTF-8");
Set the XML file indent 4 spaces Format.setindent ("");
Build an XML output factory that will format to the factory xmloutputter xmlout = new Xmloutputter (format);
try {//write the text to the factory and build a file output stream to output the data Xmlout.output (Doc, New FileOutputStream ("People.xml")); SYSTEM.OUT.PRINTLN ("Success!") ");
} catch (FileNotFoundException e) {//TODO auto-gEnerated Catch block E.printstacktrace ();
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();}} /* Run Result: <?xml version= "1.0" encoding= "UTF-8"?> <people> <student name= "John" salary= "8000"/> </ people> * * * * *

Example 2: Parsing people.xml files using Jdom

New ReadXml class

Package com.book.jdom;
Import java.io.IOException;
Import java.util.List;
Import org.jdom2.Document;
Import org.jdom2.Element;
Import org.jdom2.JDOMException;
Import Org.jdom2.input.SAXBuilder;
Read People.xml document public
class Readxml {public
static void Main (string[] args) {
//New builder parse XML
Saxbuilder sax = new Saxbuilder ();
Build a document to accept data
doc Docs;
try {
//get people.xml
doc = sax.build ("People.xml");
Gets the root node
Element people = doc.getrootelement ();
Gets the node data
list<element> List = People.getchildren () under the root node
; for (int i = 0;i<list.size (); i++) {
Element e = List.get (i);
Gets the property value
System.out.println ("Name:" +e.getattributevalue ("name") + "Salary:" +e.getattributevalue ("salary"));
Get text value
System.out.println (E.gettext ());
}
catch (Jdomexception e) {
e.printstacktrace ();
} catch (IOException e) {
e.printstacktrace ();
}}} *
* Run Result:
* Name: John salary:8000
hehe
* * * *

Parsing xml

Methods for obtaining different attribute values of multiple identical label names with Jdom &lt;?xml version= "1.0" encoding= "UTF-8"?&gt; &lt;Configuration&gt; &lt;key name= "" "&gt; &lt;value name= "Textkey" &gt;China&lt;/Value&gt; &lt;value name= "Enabled" &gt;true&lt;/Value&gt; &lt;value  Name= "Photoidwidth" &gt;38PhotoIDWidth&lt;/Value&gt; &lt;value name= "Photoidheight" &gt;38&lt;/Value&gt; &lt;key Name= "adult" &gt; &lt;value name= "crownpercent" &gt;0.10&lt;/Value&gt; &lt;value name= "Headpercent" &gt;0.60 adultheadpercent&lt;/value&gt; &lt;/Key&gt; &lt;key name= "Child" &gt; &lt;value name= "crownpercent" &gt; 0.10&lt;/value&gt; &lt;value name= "headpercent" &gt;0.60ChildHeadPercent&lt;/Value&gt; &lt;/Key&gt; &lt;/ key&gt; &lt;key name= "Australia" &gt; &lt;value name= "textkey" &gt;Australia&lt;/Value&gt; &lt;value name= "E Nabled "&gt;true&lt;/Value&gt; &lt;value name=" photoidwidth "&gt;35PhotoIDWidth&lt;/Value&gt; &lt;value name=" Ph Otoidheight "&gt;45&lt;/value&gt; &lt;key name= "adult" &gt; &lt;value name= "crownpercent" &gt;0.061&lt;/Value&gt; &lt;value Nam E= "Headpercent" &gt;0.756 "adult" headpercent&lt;/value&gt; &lt;/Key&gt; &lt;key name= "Child" &gt; &lt;val 
      UE name= "crownpercent" &gt;0.072&lt;/Value&gt; &lt;value name= "Headpercent" &gt;0.711ChildHeadPercent&lt;/Value&gt; &lt;/Key&gt; &lt;/Key&gt; &lt;key name= "Austria" &gt; &lt;value name= "Textkey" &gt;austria&lt;/value&gt
      ; &lt;value name= "Enabled" &gt;true&lt;/Value&gt; &lt;value name= "Photoidwidth" &gt;35PhotoIDWidth&lt;/Value&gt; & Lt Value name= "Photoidheight" &gt;45&lt;/Value&gt; &lt;key name= "adult" &gt; &lt;value name= "crownpercent" &gt;0.0 64&lt;/value&gt; &lt;value name= "headpercent" &gt;0.744AdultHeadPercent&lt;/Value&gt; &lt;/Key&gt; &lt; Key name= "Child" &gt; &lt;value name= "crownpercent" &gt;0.078&lt;/Value&gt; &lt;value name= "Headpercent" &gt; 0.689ChildHeadPercent&lt;/value&gt; &lt;/Key&gt; &lt;/Key&gt; &lt;/Configuration&gt; package input;
Import java.io.IOException;
Import java.util.ArrayList;
Import java.util.List;
Import org.jdom.Document;
Import org.jdom.Element;
Import org.jdom.JDOMException;
Import Org.jdom.input.SAXBuilder; public class ReadXML {/** * @param args */public static void main (string[] args) throws Jdomexception, Ioexcep
    tion {saxbuilder sb = new Saxbuilder ();
    Construct Document Object doc = Sb.build (Test.class.getClassLoader (). getResourceAsStream ("Nation.xml"));
    Gets the root element root = Doc.getrootelement ();
    Navigate to &lt;Configuration&gt;-&gt; &lt;Key&gt; list&lt;element&gt; List = Root.getchildren ("Key");
    list&lt;element&gt; children = new arraylist&lt;element&gt; ();
    list&lt;element&gt; childrens = new arraylist&lt;element&gt; ();
      for (int i = 0; i &lt; list.size (); i++) {Element element = (Element) list.get (i); System.out.print (Element.getattributevalue ("Name ")); 
      Locate to &lt;Configuration&gt;-&gt; &lt;Key&gt;-&gt; &lt;Value&gt; children = Element.getchildren ("Value");
        for (int j=0; j&lt;children.size (); j + +) {Element Elementchildren = (Element) children.get (j); Navigate to &lt;Configuration&gt;-&gt; &lt;Key&gt;-&gt; &lt;value name= "Photoidwidth" &gt; if (elementchildren.getattribu Tevalue ("Name"). Equals ("Photoidwidth")) {//Get &lt;Configuration&gt;-&gt; &lt;Key&gt;-&gt; &lt;value name= "Photo
          Idwidth "&gt; Property value System.out.print (" &lt;---------&gt; "+elementchildren.getattributevalue (" Name ")); Get &lt;Configuration&gt;-&gt; &lt;Key&gt;-&gt; &lt;value name= "photoidwidth" &gt; tags Content System.out.print ("," +e
        Lementchildren.gettext ());
      } children.clear ();
      Positioning to &lt;Configuration&gt;-&gt; &lt;Key&gt;-&gt; &lt;Key&gt; children = Element.getchildren ("Key"); for (int j=0; j&lt;children.size (); j + +) {element Elementchildren = (element) Children.get (j); Navigate to &lt;Configuration&gt;-&gt; &lt;Key&gt;-&gt; &lt;key name= "Child" &gt; If (Elementchildren.getattributevalue (" Name "). Equals (" child ")) {//Navigate to &lt;Configuration&gt;-&gt; &lt;Key&gt;-&gt; &lt;key name=" Child "&gt;-&gt; &lt;v
          alue&gt; childrens = Elementchildren.getchildren ("Value");
            for (int k=0; k&lt;childrens.size (); k++) {Element Elementchildrens = (Element) Childrens.get (k);
            Navigate to &lt;Configuration&gt;-&gt; &lt;Key&gt;-&gt; &lt;key name= "Child" &gt;-&gt; &lt;value name= "Headpercent" &gt; if (Elementchildrens.getattributevalue ("Name"). Equals ("Headpercent")) {System.out.println ("&lt;---------
            &gt; "+elementchildrens.gettext ()); Print results: china&lt;---------&gt;PhotoIDWidth,38PhotoIDWidth&lt;---------&gt;0.60ch
Ildheadpercent australia&lt;---------&gt;PhotoIDWidth,35PhotoIDWidth&lt;---------&gt;0.711childheadpercent austria&lt;---------&gt;PhotoIDWidth,35PhotoIDWidth&lt;---------&gt;0.689childheadpercent 

The above is a small set to introduce the Javaweb in the use of Jdom parsing XML method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.