使用DOM解析XML文档:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class DOMParserExample {
public static void main(String[] args) {
try {
// 1. 创建 DocumentBuilderFactory 实例
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 2. 创建 DocumentBuilder 实例
DocumentBuilder builder = factory.newDocumentBuilder();
// 3. 使用 DocumentBuilder 解析XML文件,得到 Document 对象
Document document = builder.parse("example.xml");
// 4. 获取根元素
Element root = document.getDocumentElement();
// 5. 获取子元素列表
NodeList nodeList = root.getElementsByTagName("book");
// 6. 遍历子元素
for (int i = 0; i < nodeList.getLength(); i++) {
Element book = (Element) nodeList.item(i);
String title = book.getElementsByTagName("title").item(0).getTextContent();
String author = book.getElementsByTagName("author").item(0).getTextContent();
System.out.println("Book: " + title + " by " + author);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用SAX解析XML文档:
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
public class SAXParserExample {
public static void main(String[] args) {
try {
// 1. 创建 SAXParserFactory 实例
SAXParserFactory factory = SAXParserFactory.newInstance();
// 2. 创建 SAXParser 实例
SAXParser saxParser = factory.newSAXParser();
// 3. 创建自定义的 Handler
MyHandler handler = new MyHandler();
// 4. 解析 XML 文件
saxParser.parse(new File("example.xml"), handler);
} catch (Exception e) {
e.printStackTrace();
}
}
static class MyHandler extends DefaultHandler {
boolean titleFlag = false;
boolean authorFlag = false;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("title")) {
titleFlag = true;
} else if (qName.equalsIgnoreCase("author")) {
authorFlag = true;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (titleFlag) {
System.out.println("Title: " + new String(ch, start, length));
titleFlag = false;
} else if (authorFlag) {
System.out.println("Author: " + new String(ch, start, length));
authorFlag = false;
}
}
}
}
这两个例子分别使用了DOM和SAX解析XML文档。DOM解析适合对整个XML文档进行频繁访问的情况,而SAX解析则更适合对大型XML文档进行逐行读取和处理的场景。选择解析方式取决于具体需求和文档的大小。
转载请注明出处:http://www.zyzy.cn/article/detail/475/Java