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
标签:XML,xml,java,读取,void,import,public,String From: https://www.cnblogs.com/2008nmj/p/17994115