解析XML列表常用DOM、SAX、XPath和JAXB方法;DOM適合小中型文件,SAX節(jié)省內(nèi)存處理大文件,XPath簡化節(jié)點(diǎn)查詢,JAXB實(shí)現(xiàn)對象映射。
在處理XML數(shù)據(jù)時(shí),經(jīng)常會遇到包含列表結(jié)構(gòu)的數(shù)據(jù)。解析XML中的列表需要正確讀取重復(fù)的元素節(jié)點(diǎn),并將其轉(zhuǎn)換為程序可用的結(jié)構(gòu)(如數(shù)組或列表)。下面介紹幾種常見的解析XML列表的方法,并附上實(shí)用示例。
DOM(Document Object Model) 將整個(gè)XML文檔加載到內(nèi)存中,形成樹結(jié)構(gòu),適合小到中等規(guī)模的XML文件。
步驟如下:
<books> <book> <title>Java編程思想</title> <author>Bruce Eckel</author> </book> <book> <title>Effective Java</title> <author>Joshua Bloch</author> </book> </books>
Java中使用DOM解析上述列表:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xmlString))); NodeList bookNodes = doc.getElementsByTagName("book"); for (int i = 0; i < bookNodes.getLength(); i++) { Element bookElement = (Element) bookNodes.item(i); String title = bookElement.getElementsByTagName("title").item(0).getTextContent(); String author = bookElement.getElementsByTagName("author").item(0).getTextContent(); System.out.println("書名: " + title + ", 作者: " + author); }
SAX(Simple API for XML) 是事件驅(qū)動的流式解析器,適合處理大文件,節(jié)省內(nèi)存。
關(guān)鍵點(diǎn):
DefaultHandler
類startElement
和endElement
中判斷當(dāng)前標(biāo)簽當(dāng)遇到<book>
開始時(shí)設(shè)置標(biāo)志,在結(jié)束時(shí)保存數(shù)據(jù)。
XPath 可以直接定位到指定路徑的節(jié)點(diǎn)集合,簡化列表提取過程。
示例:提取所有書名
XPath xpath = XPathFactory.newInstance().newXPath(); NodeList titles = (NodeList) xpath.compile("/books/book/title/text()").evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < titles.getLength(); i++) { System.out.println(titles.item(i).getNodeValue()); }
雖然Jsoup主要用于HTML,但某些場景下也可解析簡單XML。更推薦使用Jackson XmlMapper
或JAXB
將XML映射為Java對象。
例如,定義一個(gè)Book類:
@XmlRootElement(name = "books") @XmlAccessorType(XmlAccessType.FIELD) public class Books { @XmlElement(name = "book") private List<Book> bookList; // getter and setter } class Book { public String title; public String author; }
然后使用JAXB解組:
JAXBContext context = JAXBContext.newInstance(Books.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Books books = (Books) unmarshaller.unmarshal(new StringReader(xmlString));
基本上就這些方法。選擇哪種方式取決于XML大小、性能要求和開發(fā)環(huán)境。DOM直觀易用,SAX適合大文件,XPath查詢靈活,而JAXB更適合對象映射場景。
以上就是XML中如何解析XML列表_XML解析XML列表的方法與示例的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
每個(gè)人都需要一臺速度更快、更穩(wěn)定的 PC。隨著時(shí)間的推移,垃圾文件、舊注冊表數(shù)據(jù)和不必要的后臺進(jìn)程會占用資源并降低性能。幸運(yùn)的是,許多工具可以讓 Windows 保持平穩(wěn)運(yùn)行。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號