1. Preface
What is Jdom?
Jdom is an open source project based on a tree structure, using pure Java technology to parse, generate, serialize and operate on XML documents. It directly serves Java programming, uses the features of the java language (method overloading, collections), combines the functions of SAX and DOM, and makes parsing the original XML as simple as possible. It will be easy for us to use Jdom to parse the XML.
Advantages of Jdom:
1. Jdom is dedicated to Java technology and takes up less memory than Dom applications.
2. Jdom provides a simpler and logical basic method for accessing xml information
3. In addition to the xml file, Jdom can also access other data sources, for example, you can create classes to access data from SQL query results.
Jdom composition:
Jdom consists of 6 packages
Element class represents elements of XML document
org.jdom: The basic class to be used to parse XML files
org.jdom.adapters: Java class containing DOM adaptations
org.jdom.filter: Filter class containing xml documents
org.jdom.input: Java class that contains reading XML documents
org.jdom.output: Class containing output XML document
org.jdom.trans form: Contains Java classes that convert Jdom xml document interface 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, including the most commonly used ones such as jdom, dom4j, sax, etc.
Jdom package download: http://www.jdom.org/downloads/index.html
What the author's code here is to use java to create an xml and read an xml, which is only used as a note introduction.
2. Operation
Download the jdom package, unzip the files jdom-2.0.6.jar, jdom-2.0.6-javadoc.jar, and import the package into the lib folder. (Note, if there is any error, import all packages in Jdom)
Example 1: Create an xml file using jdom with the name people.xml
Create a 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 xml file public class CreateJdom {public static void main(String[] args) {//Define element Element people,student; people = new Element("people");student = new Element("student");//Set the attribute student.setAttribute("name", "Zhang San");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);//Read the format and assign it to the current FormatFormat format = Format.getCompactFormat();//Initialize the current format format.setEncoding("UTF-8");//Set the xml file indents format.setIndent(" ");//Build an xml output factory and give the format to the factory XMLOutputter xmlout = new XMLOutputter(format);try {//Send the written text to the factory, and create 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/*Running result:<?xml version="1.0" encoding="UTF-8"?><people><student name="Zhang San" salary="8000" /></people>* */Example 2: Use Jdom to parse people.xml file
Create a 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 parses xmlSAXBuilder sax = new SAXBuilder();//Create a document to accept data Document doc;try {//Get people.xml document doc = sax.build("people.xml");//Get root node Element people = doc.getRootElement();//Get node data under the root node List<Element> list = people.getChildren(); for(int i = 0;i<list.size();i++){Element e = list.get(i);//Get attribute value System.out.println("name: "+e.getAttributeValue("name")+" salary: "+e.getAttributeValue("salary"));//Get the text value System.out.println(e.getText());}} catch (JDOMException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}/** Running result: * name: Zhang San salary: 8000 Hehe* */Parsing xml
Method to obtain different attribute values of multiple same tag names using jdom<?xml version="1.0" encoding="UTF-8"?><Configuration> <Key Name="China"> <Value Name="TextKey">China</Value> <Value Name="Enabled">true</Value> <Value Name="PhotoIDWidth">38PhotoIDWidth</Value> <Value Name="PhotoIDHeight">38</Value> <Key Name="Adult"> <Value Name="CrownPercent">0.10</Value> <Value Name="HeadPercent">0.60AdultHeadPercent</Value> </Key> <Key Name="Child"> <Value Name="CrownPercent">0.10</Value> <Value Name="HeadPercent">0.60ChildHeadPercent</Value> </Key> </Key> <Key Name="Australia"> <Value Name="TextKey">Australia</Value> <Value Name="Enabled">true</Value> <Value Name="PhotoIDWidth">35PhotoIDWidth</Value> <Value Name="PhotoIDHeight">45</Value> <Key Name="Adult"> <Value Name="CrownPercent">0.061</Value> <Value Name="HeadPercent">0.756"Adult"HeadPercent</Value> </Key> <Key Name="Child"> <Value Name="CrownPercent">0.072</Value> <Value Name="HeadPercent">0.711ChildHeadPercent</Value> </Key> <Key Name="Austria"> <Value Name="TextKey">Austria</Value> <Value Name="Enabled">true</Value> <Value Name="PhotoIDWidth">35PhotoIDWidth</Value> <Value Name="PhotoIDHeight">45</Value> <Key Name="Adult"> <Value Name="CrownPercent">0.064</Value> <Value Name="HeadPercent">0.744AdultHeadPercent</Value> </Key> <Key Name="Child"> <Value Name="CrownPercent">0.078</Value> <Value Name="HeadPercent">0.689ChildHeadPercent</Value> </Key> </Key></Configuration>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, IOException { SAXBuilder sb = new SAXBuilder(); //Construct document object Document doc = sb.build(Test.class.getClassLoader().getResourceAsStream("nation.xml")); //Get the root element Element root = doc.getRootElement(); //Locate <Configuration> -> <Key> List<Element> list = root.getChildren("Key"); List<Element> children = new ArrayList<Element>(); List<Element> childrens = new ArrayList<Element>(); for (int i = 0; i < list.size(); i++) { Element element = (Element) list.get(i); System.out.print(element.getAttributeValue("Name")); //Locate <Configuration> -> <Key> -> <Value> children = element.getChildren("Value"); for(int j=0; j<children.size(); j++){ Element elementChildren = (Element) children.get(j); //Locate <Configuration> -> <Key> -> <Value Name="PhotoIDWidth"> if(elementChildren.getAttributeValue("Name").equals("PhotoIDWidth")){ //Get<Configuration> -> <Key> -> <Value Name="PhotoIDWidth"> Attribute value System.out.print("<-----------------""+elementChildren.getAttributeValue("Name")); //Get the contents of <Configuration> -> <Key> -> <Value Name="PhotoIDWidth"> tag System.out.print(","+elementChildren.getText()); } } children.clear(); //Locate <Configuration> -> <Key> -> <Key> children = element.getChildren("Key"); for(int j=0; j<children.size(); j++){ Element elementChildren = (Element)children.get(j); //Locate <Configuration> -> <Key> -> <Key Name="Child"> if(elementChildren.getAttributeValue("Name").equals("Child")){ //Locate to <Configuration> -> <Key> -> <Key Name="Child"> -> <Value> childrens = elementChildren.getChildren("Value"); for(int k=0; k<childrens.size(); k++){ Element elementChildrens = (Element)childrens.get(k); //Locate to <Configuration> -> <Key> -> <Key Name="Child"> -> <Value Name="HeadPercent"> if(elementChildrens.getAttributeValue("Name").equals("HeadPercent")){ System.out.println("<----------->"+elementChildrens.getText()); } } } } } }}打印结果:China<--------->PhotoIDWidth,38PhotoIDWidth<--------->0.60ChildHeadPercentAustralia<--------->PhotoIDWidth,35PhotoIDWidth<--------->0.711ChildHeadPercentAustria<--------->PhotoIDWidth,35PhotoIDWidth<--------->0.689ChildHeadPercentThe above is the method of using Jdom to parse XML in Java web introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!