Java

如何在java中解析xml文件

小樊
82
2024-09-28 18:03:43
栏目: 编程语言

在Java中解析XML文件,可以使用以下几种方法:

  1. 使用Java内置的DOM解析器(DocumentBuilderFactory和DocumentBuilder)
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] args) {
        try {
            File inputFile = new File("input.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();

            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());

            NodeList nList = doc.getElementsByTagName("student");
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    System.out.println("Student ID: " + eElement.getElementsByTagName("id").item(0).getTextContent());
                    System.out.println("Student Name: " + eElement.getElementsByTagName("name").item(0).getTextContent());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  1. 使用Java内置的SAX解析器(SAXParserFactory和SAXParser)
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Main {
    public static void main(String[] args) {
        try {
            File inputFile = new File("input.xml");
            SAXParserFactory saxFactory = SAXParserFactory.newInstance();
            SAXParser saxParser = saxFactory.newSAXParser();
            MyHandler handler = new MyHandler();
            saxParser.parse(inputFile, handler);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class MyHandler extends DefaultHandler {
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.println("Start Element: " + qName);
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String content = new String(ch, start, length).trim();
        if (content.length() > 0) {
            System.out.println("Content: " + content);
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.println("End Element: " + qName);
    }
}
  1. 使用第三方库Jackson XML

首先,需要在项目中添加Jackson XML依赖。如果使用Maven,可以在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.12.3</version>
</dependency>

然后,可以使用以下代码解析XML文件:

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.File;
import java.io.IOException;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        try {
            File inputFile = new File("input.xml");
            XmlMapper xmlMapper = new XmlMapper();
            Map<String, Object> resultMap = xmlMapper.readValue(inputFile, Map.class);

            System.out.println("Root element: " + resultMap.get("root"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这些方法都可以用于解析XML文件,具体选择哪种方法取决于项目需求和性能要求。

0
看了该问题的人还看了