XMLStreamReader:
1. DOM(Document Object Model)方式:DOM将整个XML文档加载到内存中,形成一颗树状结构,然后通过操作这个树状结构来获取所需要的数据。示例代码如下:
import javax.xml.parsers.*; import org.w3c.dom.*; public class XMLParser { public static void main(String[] args) throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // 从文件路径或URL创建输入流 InputStream inputStream = new FileInputStream("path/to/file.xml"); Document document = builder.parse(inputStream); Element rootElement = document.getDocumentElement(); NodeList nodeList = rootElement.getElementsByTagName("tagName"); for (int i=0; i<nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { Element element = (Element) node; String attributeValue = element.getAttribute("attributeName"); String textContent = element.getTextContent(); System.out.println("Attribute Value: " + attributeValue); System.out.println("Text Content: " + textContent); } } } }
2. SAX(Simple API for XML)方式:SAX是基于事件驱动的API,在处理大型XML文件时效果更好。它按行读取XML文件,当发现特定标记时会触发相应的事件处理程序。示例代码如下:
import javax.xml.parsers.*; import org.xml.sax.*; import org.xml.sax.helpers.*; public class XMLHandler extends DefaultHandler { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); if ("tagName".equalsIgnoreCase(qName)) { String attributeValue = attributes.getValue("attributeName"); System.out.println("Attribute Value: " + attributeValue); } } @Override public void characters(char ch[], int start, int length) throws SAXException { super.characters(ch, start, length); String content = new String(ch, start, length).trim(); if (!content.isEmpty()) { System.out.println("Text Content: " + content); } } public static void main(String[] args) throws Exception { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); XMLReader reader = parser.getXMLReader(); XMLHandler handler = new XMLHandler(); reader.setContentHandler(handler); // 从文件路径或URL创建输入流 InputSource source = new InputSource("path/to/file.xml"); reader.parse(source); } }
除了上述两种常用的方式外,还有其他第三方库如JDom、Xerces等也提供了类似功能的API。
参考:百度AI
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2021-01-29 SQL Server设置默认值
2020-01-29 The 1st Challenge on Remote Physiological Signal Sensing (RePSS) CVPR2020人脸心率估计竞赛
2019-01-29 faceswap安装说明
2019-01-29 jupyterlab notebook区别
2019-01-29 数据分析工具R和RStudio入门介绍
2017-01-29 OpenGL + MFC