How Java uses JDOM parser to read XML files and obtain Document objects

To read an XML file and obtain a Document object using a JDOM parser, follow the following steps: 1. Add Maven dependency: Add the following dependency relationships in the pom.xml file of the project: <dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.6</version> </dependency> 2. Create an XML sample file: Assuming we have an XML file called "example. xml", the content is as follows: <?xml version="1.0" encoding="UTF-8"?> <root> <element1>Hello</element1> <element2>World</element2> <element3> <subelement>Example</subelement> </element3> </root> 3. Use the JDOM parser to read the XML file and obtain the Document object: import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import java.io.File; public class JDOMExample { public static void main(String[] args) { try { File file = new File("example.xml"); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(file); Element rootElement = document.getRootElement(); System.out.println("Root element name: " + rootElement.getName()); Element element1 = rootElement.getChild("element1"); System.out.println("element1 value: " + element1.getValue()); Element element3 = rootElement.getChild("element3"); Element subElement = element3.getChild("subelement"); System.out.println("subelement value: " + subElement.getValue()); } catch (Exception e) { e.printStackTrace(); } } } The above code first specifies the XML file to be parsed through the File object, and then creates a new XML parser using SAXBuilder. Next, call the 'saxBuilder. build (file)' method to parse the file and return a Document object. By using the Document object, we can obtain the root element, child element, and print their values. Note that this example is only a simple demonstration, and if more complex XML operations are required, more detailed code may be required.