How Java uses a DOM parser to read XML files

To use the DOM parser to read XML files, you can use the DocumentBuilder class under the javax.xml.parsers package in the Java Standard library. The following are the steps to read an XML file using a DOM parser: 1. Create a DocumentBuilderFactory object, which is used to obtain an instance of the DOM parser. 2. Call the newDocumentBuilder() method of DocumentBuilderFactory to create a DocumentBuilder object. 3. Use the parse() method of the DocumentBuilder object to parse the XML file and convert it into a Document object. 4. Through the Document object, elements and attributes in XML files can be obtained, and then operations can be performed on XML files. The following is an example of Java code that reads an XML file using a DOM parser: import org.w3c.dom.*; import javax.xml.parsers.*; public class DOMParserExample { public static void main(String[] args) throws Exception { //Create a DocumentBuilderFactory object DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Create a DocumentBuilder object DocumentBuilder builder = factory.newDocumentBuilder(); //Parsing XML files using DocumentBuilder objects to obtain Document objects Document document = builder.parse("example.xml"); //Get the root element of the XML file Element rootElement = document.getDocumentElement(); //Obtain sub elements under the root element NodeList nodeList = rootElement.getChildNodes(); //Traverse sub elements for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { Element element = (Element) node; //Obtain the tag name of the element String tagName = element.getTagName(); //Get the text content of the element String textContent = element.getTextContent(); System.out.println("Tag Name: " + tagName); System.out.println("Text Content: " + textContent); } } } } The example XML file (example.xml) used in the above code is as follows: <?xml version="1.0" encoding="UTF-8"?> <root> <item>Item 1</item> <item>Item 2</item> <item>Item 3</item> </root> Before using this code, it is necessary to ensure that the following Maven dependencies are added to the pom.xml file of the project: <dependencies> <dependency> <groupId>javax.xml.parsers</groupId> <artifactId>jaxp-api</artifactId> <version>1.4.2</version> </dependency> </dependencies> This way, you can use the DOM parser to read the XML file.