XML + 4种常见解析方式

XML(eXtensible Markup Language)是一种常用于存储和交换数据的标记语言。在Java中,有多种方式可以解析XML文档。以下是四种常见的XML解析方式:

1. **DOM解析(Document Object Model):**
   - **优点:** 完整的树形结构,方便对文档进行任何修改和操作。
   - **缺点:** 内存消耗较大,不适用于处理大型XML文件。

   ```java
   // 使用javax.xml.parsers 包中的 DocumentBuilder 来解析 XML
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = factory.newDocumentBuilder();
   Document document = builder.parse(new File("example.xml"));
   ```

代码:

private static void domTest2() throws ParserConfigurationException, IOException, SAXException {
    try {
        // Load the XML file
        File xmlFile = new File("D:\\CodeAll\\code\\Exercies\\src\\huizhi\\xmltest\\StudentTable.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        org.w3c.dom.Document document = dBuilder.parse(xmlFile);
        document.getDocumentElement().normalize();

        // Get the root element
        org.w3c.dom.Element rootElement = document.getDocumentElement();

        // Get all student nodes
        NodeList studentList = rootElement.getElementsByTagName("student");

        for (int i = 0; i < studentList.getLength(); i++) {
            Node studentNode = studentList.item(i);
            if (studentNode.getNodeType() == Node.ELEMENT_NODE) {
                Element studentElement = (Element) studentNode;

                // Extract data from student node
                String name = studentElement.getElementsByTagName("name").item(0).getTextContent();
                String age = studentElement.getElementsByTagName("age").item(0).getTextContent();
                String grade = studentElement.getElementsByTagName("grade").item(0).getTextContent();
                String subject = studentElement.getElementsByTagName("subject").item(0).getTextContent();

                // Print extracted information
                System.out.println("Name: " + name);
                System.out.println("Age: " + age);
                System.out.println("Grade: " + grade);
                System.out.println("Subject: " + subject);
                System.out.println("------------------------");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2. **SAX解析(Simple API for XML):**
   - **优点:** 逐行读取,适用于大型XML文件,内存消耗小。
   - **缺点:** 不支持文档的修改操作。

   ```java
   // 使用 org.xml.sax 包中的 SAXParser 来解析 XML
   SAXParserFactory factory = SAXParserFactory.newInstance();
   SAXParser parser = factory.newSAXParser();
   XMLHandler handler = new XMLHandler();
   parser.parse(new File("example.xml"), handler);
   ```

代码:

private static void saxTest() {
    try {
        // Create a SAXParserFactory
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();

        // Create a handler for SAX events
        DefaultHandler handler = new DefaultHandler() {
            boolean inStudent = false;
            boolean inName = false;
            boolean inAge = false;
            boolean inGrade = false;
            boolean inSubject = false;

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                if (qName.equalsIgnoreCase("student")) {
                    inStudent = true;
                } else if (qName.equalsIgnoreCase("name")) {
                    inName = true;
                } else if (qName.equalsIgnoreCase("age")) {
                    inAge = true;
                } else if (qName.equalsIgnoreCase("grade")) {
                    inGrade = true;
                } else if (qName.equalsIgnoreCase("subject")) {
                    inSubject = true;
                }
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (inName) {
                    System.out.println("Name: " + new String(ch, start, length));
                } else if (inAge) {
                    System.out.println("Age: " + new String(ch, start, length));
                } else if (inGrade) {
                    System.out.println("Grade: " + new String(ch, start, length));
                } else if (inSubject) {
                    System.out.println("Subject: " + new String(ch, start, length));
                }
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (qName.equalsIgnoreCase("student")) {
                    inStudent = false;
                } else if (qName.equalsIgnoreCase("name")) {
                    inName = false;
                } else if (qName.equalsIgnoreCase("age")) {
                    inAge = false;
                } else if (qName.equalsIgnoreCase("grade")) {
                    inGrade = false;
                } else if (qName.equalsIgnoreCase("subject")) {
                    inSubject = false;
                }
            }
        };

        // Parse the XML file using the handler
        saxParser.parse(new File("D:\\CodeAll\\code\\Exercies\\src\\huizhi\\xmltest\\StudentTable.xml"), handler);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

3. **JDOM解析:**
   - **优点:** 操作简单,使用Java集合,比DOM更直观。
   - **缺点:** 内存占用较大。

   ```java
   // 使用 org.jdom2 包中的 SAXBuilder 来解析 XML
   SAXBuilder builder = new SAXBuilder();
   Document document = builder.build(new File("example.xml"));
   ```

private static void jdomTest() {
    try {
        // Load the XML file
        File xmlFile = new File("D:\\CodeAll\\code\\Exercies\\src\\huizhi\\xmltest\\StudentTable.xml");

        // Create a JDOM document
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document =  saxBuilder.build(xmlFile);

        // Get the root element
        Element rootElement = document.getRootElement();

        // Get all student elements
        List studentList = rootElement.getChildren("student");

        for (Element studentElement : studentList) {
            // Extract data from student element
            String name = studentElement.getChildText("name");
            String age = studentElement.getChildText("age");
            String grade = studentElement.getChildText("grade");
            String subject = studentElement.getChildText("subject");

            // Print extracted information
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Grade: " + grade);
            System.out.println("Subject: " + subject);
            System.out.println("------------------------");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

4. **StAX解析(Streaming API for XML):**
   - **优点:** 基于事件驱动,适用于大型XML文件,内存消耗小。
   - **缺点:** 编程较为复杂。

   ```java
   // 使用 javax.xml.stream 包中的 XMLInputFactory 来解析 XML
   XMLInputFactory factory = XMLInputFactory.newInstance();
   XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream("example.xml"));
   ```

选择解析方式通常取决于具体的应用场景和需求。如果需要对XML文档进行修改,DOM解析可能更合适;如果处理大型XML文件,可以选择SAX或StAX以减小内存开销;而JDOM则提供了一种较为简单的API。

private static void dom4jTest() {
    try {
        // Load the XML file using dom4j
        File xmlFile = new File("D:\\CodeAll\\code\\Exercies\\\\src\\huizhi\\xmltest\\StudentTable.xml");
        SAXReader reader = new SAXReader();
        Document document = reader.read(xmlFile);

        // Get the root element
        Element rootElement = document.getRootElement();

        // Get all student elements
        List studentList = rootElement.elements("student");

        // Iterate through each student
        for (Element studentElement : studentList) {
            // Extract data from student element
            String name = studentElement.elementText("name");
            String age = studentElement.elementText("age");
            String grade = studentElement.elementText("grade");
            String subject = studentElement.elementText("subject");

            // Print student information
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Grade: " + grade);
            System.out.println("Subject: " + subject);
            System.out.println("------------------------");
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

XML + 4种常见解析方式_第1张图片

你可能感兴趣的:(xml)