在 Java 中解析 XML 文件有多种方式,下面我会介绍几种常见的实现方式,包括使用 DOM、SAX、JAXB 和 StAX。我会为每种方式提供步骤流程和相应的代码示例,以及 Maven 和 Gradle 的依赖坐标。
DOM (Document Object Model) 是一种将整个 XML 文档加载到内存中的方式,以树状结构表示文档,便于对文档进行操作。
步骤流程:
示例代码:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
public class DomParserExample {
public static void main(String[] args) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("path/to/your/file.xml");
Element root = document.getDocumentElement();
NodeList nodeList = root.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String tagName = element.getTagName();
// Process element data
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Maven 依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
Gradle 依赖:
implementation 'org.apache.commons:commons-lang3:3.12.0'
SAX (Simple API for XML) 是一种基于事件驱动的解析方式,逐行解析文档,适用于大型文档,不需要将整个文档加载到内存中。
步骤流程:
示例代码:
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 SaxParserExample {
public static void main(String[] args) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
// Process start of element
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
// Process element content
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// Process end of element
}
};
parser.parse("path/to/your/file.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Maven 依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
Gradle 依赖:
implementation 'org.apache.commons:commons-lang3:3.12.0'
JAXB (Java Architecture for XML Binding) 允许将 XML 数据绑定到 Java 对象上,实现了将 XML 文件转换成 Java 对象和将 Java 对象转换成 XML 文件的操作。
步骤流程:
示例代码:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
public class JaxbParserExample {
public static void main(String[] args) {
try {
JAXBContext context = JAXBContext.newInstance(YourClass.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
YourClass obj = (YourClass) unmarshaller.unmarshal(new File("path/to/your/file.xml"));
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(obj, new File("path/to/output/file.xml"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Maven 依赖:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.4.0-b180830.0359</version>
</dependency>
Gradle 依赖:
implementation 'javax.xml.bind:jaxb-api:2.4.0-b180830.0359'
StAX (Streaming API for XML) 提供一种基于事件迭代的方式来处理 XML 数据,适用于大型文档,允许同时读写 XML。
步骤流程:
示例代码:
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.FileInputStream;
public class StaxParserExample {
public static void main(String[] args) {
try {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream("path/to/your/file.xml"));
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamReader.START_ELEMENT:
String elementName = reader.getLocalName();
// Process start of element
break;
case XMLStreamReader.CHARACTERS:
String text = reader.getText();
// Process element content
break;
case XMLStreamReader.END_ELEMENT:
// Process end of element
break;
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
}
Maven 依赖:
<dependency>
<groupId>javax.xml.stream</groupId>
<artifactId>stax-api</artifactId>
<version>1.0-2</version>
</dependency>
Gradle 依赖:
implementation 'javax.xml.stream:stax-api:1.0-2'
以上是四种常见的 XML 解析方式,每种方式都有不同的应用场景和适用性。您可以根据您的项目需求和偏好选择其中之一来解析 XML 文件。