JDOM provides a very excellent Java XML API to more conveniently read, modify, and generate XML documents. JDOM also provides wrapper classes for users to choose specific implementations from SAX, DOM, STAX event parsing, and STAX stream parsing.
In this tutorial, we learn to use JDOM to read XML file information and convert it into Java objects.
JDOM is not part of the standard JDK, so to use JDOM you need to download the JDOM binary package from the official website. After downloading, add the JDOM Jar package to the classpath of the project.
JDOM provides a wrapper class for us to choose the underlying XML parsing API. It provides four important classes that we can use to obtain the Document object of JDOM. The JDOM Document object provides very useful methods to get the root element, list of child elements, attribute values, etc.
Important classes of JDOM: org.jdom2.input.DOMBuilder:
Use the DOM parsing mechanism to parse XML and convert it into a JDOM Document object. org.jdom2.input.SAXBuilder:
Use the SAX parsing mechanism to parse XML and convert it to a JDOM Document. org.jdom2.input.StAXEventBuilder
and org.jdom2.input.StAXStreamBuilder
have similar functions to the previous two and will not be described again. org.jdom2.Document
The JDOM Document object provides useful methods to obtain the root element, read or modify the element content, etc. We will use it to obtain the root element of XML. org.jdom2.Document
Provides useful methods to obtain child element collections, obtain child element values, obtain attribute values and other operations.
Next we start using the case program to read the XML file and generate Java objects.
employees.xml
<?xml version="1.0" encoding="UTF-8"?><Employees> <Employee id="1"> <age>29</age> <name>Pankaj</name> <gender>Male</gender> <role>Java Developer</role> </Employee> <Employee id="2"> <age>35</age> <name>Lisa</name> <gender>Female</gender> <role>CEO</role> </Employee> <Employee id="3"> <age>40</age> <name>Tom</name> <gender>Male</gender> <role>Manager</role> </Employee></Employees>
This xml file stores employee information. We use the Employee class to represent employees.
package com.journaldev.xml;public class Employee { private int id; private String name; private String gender; private int age; private String role; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } @Override public String toString() { return "Employee:: ID="+this.id+" Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender + " Role=" + this.role; } }
Then use DOMBuilder in the test program to read the XML file and generate a collection of Employee objects.
JDOMXMLReader.java
package com.journaldev.xml.jdom; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.DOMBuilder; import org.jdom2.input.SAXBuilder; import org.jdom2.input.StAXEventBuilder; import org.jdom2.input.StAXStreamBuilder; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.journaldev.xml.Employee; public class JDOMXMLReader { public static void main(String[] args) { final String fileName = "/Users/pankaj/employees.xml"; org.jdom2.Document jdomDoc; try { //we can create JDOM Document from DOM, SAX and STAX Parser Builder classes jdomDoc = useDOMParser(fileName); Element root = jdomDoc.getRootElement(); List<Element> empListElements = root.getChildren("Employee"); List<Employee> empList = new ArrayList<>(); for (Element empElement : empListElements) { Employee emp = new Employee(); emp.setId(Integer.parseInt(empElement.getAttributeValue("id"))); emp.setAge(Integer.parseInt(empElement.getChildText("age"))); emp.setName(empElement.getChildText("name")); emp.setRole(empElement.getChildText("role")); emp.setGender(empElement.getChildText("gender")); empList.add(emp); } //lets print Employees list information for (Employee emp : empList) System.out.println(emp); } catch (Exception e) { e.printStackTrace(); } } //Get JDOM document from DOM Parser private static org.jdom2.Document useDOMParser(String fileName) throws ParserConfigurationException, SAXException, IOException { //creating DOM Document DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new File(fileName)); DOMBuilder domBuilder = new DOMBuilder(); return domBuilder.build(doc); } }
As you can see, here I use the DOM parsing wrapper class to obtain the JDOM Document object.
Run the program output:
Employee:: ID=1 Name=Pankaj Age=29 Gender=Male Role=Java DeveloperEmployee:: ID=2 Name=Lisa Age=35 Gender=Female Role=CEOEmployee:: ID=3 Name=Tom Age=40 Gender=Male Role=Manager
We can also use the SAX and STAX parsing mechanisms to complete. We can use the following method to complete:
/Get JDOM document from SAX Parserprivate static org.jdom2.Document useSAXParser(String fileName) throws JDOMException, IOException { SAXBuilder saxBuilder = new SAXBuilder(); return saxBuilder.build(new File(fileName)); } //Get JDOM Document from STAX Stream Parser or STAX Event Parserprivate static org.jdom2. Document useSTAXParser(String fileName, String type) throws FileNotFoundException, XMLStreamException, JDOMException{ if(type.equalsIgnoreCase("stream")){ StAXStreamBuilder staxBuilder = new StAXStreamBuilder(); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new FileInputStream(fileName)); return staxBuilder.build(xmlStreamReader); } StAXEventBuilder staxBuilder = new StAXEventBuilder(); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileInputStream(fileName)); return staxBuilder.build(xmlEventReader); }
Running the program will get the same output, because We just use different wrapper classes, but the JDOM Document objects obtained are the same.
The advantage of using JDOM is that we can easily switch the underlying parsing mechanism without changing the processing code.
JDOM provides a very excellent Java XML API to more conveniently read, modify, and generate XML documents. JDOM also provides wrapper classes for users to choose specific implementations from SAX, DOM, STAX event parsing, and STAX stream parsing.
In this tutorial, we learn to use JDOM to read XML file information and convert it into Java objects.
JDOM is not part of the standard JDK, so to use JDOM you need to download the JDOM binary package from the official website. After downloading, add the JDOM Jar package to the classpath of the project.
JDOM provides a wrapper class for us to choose the underlying XML parsing API. It provides four important classes that we can use to obtain the Document object of JDOM. The JDOM Document object provides very useful methods to get the root element, list of child elements, attribute values, etc.
Important classes of JDOM: org.jdom2.input.DOMBuilder:
Use the DOM parsing mechanism to parse XML and convert it into a JDOM Document object. org.jdom2.input.SAXBuilder:
Use the SAX parsing mechanism to parse XML and convert it to a JDOM Document. org.jdom2.input.StAXEventBuilder
and org.jdom2.input.StAXStreamBuilder
have similar functions to the previous two and will not be described again. org.jdom2.Document
The JDOM Document object provides useful methods to obtain the root element, read or modify the element content, etc. We will use it to obtain the root element of XML. org.jdom2.Document
Provides useful methods to obtain child element collections, obtain child element values, obtain attribute values and other operations.
Next we start using the case program to read the XML file and generate Java objects.
employees.xml
<?xml version="1.0" encoding="UTF-8"?><Employees> <Employee id="1"> <age>29</age> <name>Pankaj</name> <gender>Male</gender> <role>Java Developer</role> </Employee> <Employee id="2"> <age>35</age> <name>Lisa</name> <gender>Female</gender> <role>CEO</role> </Employee> <Employee id="3"> <age>40</age> <name>Tom</name> <gender>Male</gender> <role>Manager</role> </Employee></Employees>
This xml file stores employee information. We use the Employee class to represent employees.
package com.journaldev.xml; public class Employee { private int id; private String name; private String gender; private int age; private String role; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } @Override public String toString() { return "Employee:: ID="+this.id+" Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender + " Role=" + this.role; } }
Then use DOMBuilder in the test program to read the XML file and generate a collection of Employee objects.
JDOMXMLReader.java
package com.journaldev.xml.jdom; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException;import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jdom2.Element;import org.jdom2.JDOMException; import org.jdom2.input.DOMBuilder; import org.jdom2.input.SAXBuilder; import org.jdom2.input.StAXEventBuilder; import org.jdom2.input.StAXStreamBuilder; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.journaldev.xml.Employee; public class JDOMXMLReader { public static void main(String[] args) { final String fileName = "/Users/pankaj/employees.xml"; org.jdom2.Document jdomDoc; try { //we can create JDOM Document from DOM, SAX and STAX Parser Builder classes jdomDoc = useDOMParser(fileName); Element root = jdomDoc.getRootElement(); List<Element> empListElements = root.getChildren("Employee"); List<Employee> empList = new ArrayList<>(); for (Element empElement : empListElements) { Employee emp = new Employee(); emp.setId(Integer.parseInt(empElement.getAttributeValue("id"))); emp.setAge(Integer.parseInt(empElement.getChildText("age"))); emp.setName(empElement.getChildText("name")); emp.setRole(empElement.getChildText("role")); emp.setGender(empElement.getChildText("gender")); empList.add(emp); } //lets print Employees list information for (Employee emp : empList) System.out.println(emp); } catch (Exception e) { e.printStackTrace(); } } //Get JDOM document from DOM Parser private static org.jdom2.Document useDOMParser(String fileName) throws ParserConfigurationException, SAXException, IOException { //creating DOM Document DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new File(fileName)); DOMBuilder domBuilder = new DOMBuilder(); return domBuilder.build(doc); } }
As you can see, here I use the DOM parsing wrapper class to obtain the JDOM Document object.
Output of running the program:
Employee:: ID=1 Name=Pankaj Age=29 Gender=Male Role=Java DeveloperEmployee:: ID=2 Name=Lisa Age=35 Gender=Female Role=CEOEmployee:: ID=3 Name=Tom Age=40 Gender=Male Role=Manager
We can also use the SAX and STAX parsing mechanisms to complete. We can use the following method to complete:
/Get JDOM document from SAX Parserprivate static org.jdom2.Document useSAXParser(String fileName) throws JDOMException, IOException { SAXBuilder saxBuilder = new SAXBuilder(); return saxBuilder.build(new File(fileName)); } //Get JDOM Document from STAX Stream Parser or STAX Event Parserprivate static org.jdom2.Document useSTAXParser(String fileName, String type) throws FileNotFoundException, XMLStreamException, JDOMException{ if(type.equalsIgnoreCase("stream")){ StAXStreamBuilder staxBuilder = new StAXStreamBuilder(); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new FileInputStream(fileName)); return staxBuilder.build(xmlStreamReader); } StAXEventBuilder staxBuilder = new StAXEventBuilder(); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileInputStream(fileName)); return staxBuilder.build(xmlEventReader); }
Running the program will get the same output, because We just use different wrapper classes, but the JDOM Document objects obtained are the same.
The advantage of using JDOM is that we can easily switch the underlying parsing mechanism without changing the processing code.
The above is the content of Java&Xml tutorial (6) using JDOM to parse XML files. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

RSS documents are a simple subscription mechanism to publish content updates through XML files. 1. The RSS document structure consists of and elements and contains multiple elements. 2. Use RSS readers to subscribe to the channel and extract information by parsing XML. 3. Advanced usage includes filtering and sorting using the feedparser library. 4. Common errors include XML parsing and encoding issues. XML format and encoding need to be verified during debugging. 5. Performance optimization suggestions include cache RSS documents and asynchronous parsing.

RSS and XML are still important in the modern web. 1.RSS is used to publish and distribute content, and users can subscribe and get updates through the RSS reader. 2. XML is a markup language and supports data storage and exchange, and RSS files are based on XML.

RSS enables multimedia content embedding, conditional subscription, and performance and security optimization. 1) Embed multimedia content such as audio and video through tags. 2) Use XML namespace to implement conditional subscriptions, allowing subscribers to filter content based on specific conditions. 3) Optimize the performance and security of RSSFeed through CDATA section and XMLSchema to ensure stability and compliance with standards.

RSS is an XML-based format used to publish frequently updated data. As a web developer, understanding RSS can improve content aggregation and automation update capabilities. By learning RSS structure, parsing and generation methods, you will be able to handle RSSfeeds confidently and optimize your web development skills.

RSS chose XML instead of JSON because: 1) XML's structure and verification capabilities are better than JSON, which is suitable for the needs of RSS complex data structures; 2) XML was supported extensively at that time; 3) Early versions of RSS were based on XML and have become a standard.

RSS is an XML-based format used to subscribe and read frequently updated content. Its working principle includes two parts: generation and consumption, and using an RSS reader can efficiently obtain information.

The core structure of RSS documents includes XML tags and attributes. The specific parsing and generation steps are as follows: 1. Read XML files, process and tags. 2. Extract,,, etc. tag information. 3. Handle custom tags and attributes to ensure version compatibility. 4. Use cache and asynchronous processing to optimize performance to ensure code readability.

The main differences between JSON, XML and RSS are structure and uses: 1. JSON is suitable for simple data exchange, with a simple structure and easy to parse; 2. XML is suitable for complex data structures, with a rigorous structure but complex parsing; 3. RSS is based on XML and is used for content release, standardized but limited use.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
