在 Java 中解析 XML 有多种方式,以下是其中几种常见的实现方式,包括 DOM 解析、SAX 解析、和 StAX 解析。每种方式的步骤流程、示例代码以及对应的 Maven 和 Gradle 依赖坐标如下:
DOM(Document Object Model)解析方式将整个 XML 文档加载到内存中构建成一个树状结构,可以方便地对其进行增删改查操作。
步骤流程:
DocumentBuilderFactory
对象。DocumentBuilderFactory
创建一个 DocumentBuilder
对象。DocumentBuilder
解析 XML 文件,获得 Document
对象。Document
对象获取元素和属性信息。示例代码:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.*;
public class DOMParserExample {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("example.xml");
Element rootElement = document.getDocumentElement();
NodeList nodeList = rootElement.getElementsByTagName("book");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element bookElement = (Element) node;
String title = bookElement.getElementsByTagName("title").item(0).getTextContent();
String author = bookElement.getElementsByTagName("author").item(0).getTextContent();
System.out.println("Title: " + title + ", Author: " + author);
}
}
}
}
Maven 依赖:
<dependency>
<groupId>javax.xml</groupId>
<artifactId>javax.xml-api</artifactId>
<version>1.0.1</version>
</dependency>
Gradle 依赖:
implementation 'javax.xml:javax.xml-api:1.0.1'
SAX(Simple API for XML)解析方式是一种基于事件的解析方式,逐行读取 XML 文档,通过事件回调处理每个元素。
步骤流程:
SAXParserFactory
对象。SAXParserFactory
创建一个 SAXParser
对象。DefaultHandler
类来处理事件。SAXParser
解析 XML 文件,通过事件回调处理元素。示例代码:
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.File;
public class SAXParserExample {
public static void main(String[] args) throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean title = false;
boolean author = false;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("title")) {
title = true;
} else if (qName.equalsIgnoreCase("author")) {
author = true;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (title) {
System.out.println("Title: " + new String(ch, start, length));
title = false;
} else if (author) {
System.out.println("Author: " + new String(ch, start, length));
author = false;
}
}
};
saxParser.parse(new File("example.xml"), handler);
}
}
Maven 依赖:
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.5.2</version>
</dependency>
Gradle 依赖:
implementation 'org.apache.maven.plugins:maven-javadoc-plugin:3.5.2'
StAX(Streaming API for XML)解析方式是一种基于迭代的解析方式,通过游标逐个处理 XML 元素。
步骤流程:
XMLInputFactory
对象。XMLInputFactory
创建一个 XMLStreamReader
对象。示例代码:
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import java.io.FileInputStream;
public class StAXParserExample {
public static void main(String[] args) throws Exception {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream("example.xml"));
String title = "";
String author = "";
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamConstants.START_ELEMENT:
String elementName = reader.getLocalName();
if (elementName.equalsIgnoreCase("title")) {
title = reader.getElementText();
} else if (elementName.equalsIgnoreCase("author")) {
author = reader.getElementText();
}
break;
case XMLStreamConstants.END_ELEMENT:
if (reader.getLocalName().equalsIgnoreCase("book")) {
System.out.println("Title: " + title + ", Author: " + author);
title = "";
author = "";
}
break;
}
}
reader.close();
}
}
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'
请注意,示例代码中的 "example.xml"
应替换为你要解析的实际 XML 文件的路径。这些示例代码可以帮助你入门不同的 XML 解析方式,并根据你的需求选择适合的方式。同时,为了便于更好的理解和学习,建议你根据自己的项目需求进一步深入学习和实践。