學習下解析 xml 文件,這里用到了 org.dom4j 這個 jar 包,使用 eclipse 沒有這個包的小伙伴可以去下個 jar 包,然后復制到項目路徑下,右鍵 jar 包后 build path,add build path 即可。
來引入相關依賴:
import java.io.File; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader;
注意會拋錯,這里 throws 一下:
public static void main (String[] args) throws Exception{ }
初始化變量:(這里我們使用的是 List 列表的方式進行解析)
SAXReader reader = new SAXReader(); File file = new File("***.xml"); Document document = reader.read(file); Element root = document.getRootElement(); List<Element> childElements = root.elements();
循環進行打印:
for (Element child : childElements) { List<Attribute> attributeList = child.attributes(); for(Attribute attr : attributeList) { System.out.println(attr.getName() + ": " + attr.getValue()); } List<Element> elementList = child.elements(); for (Element ele : elementList) { System.out.println(ele.getName() + ": " + ele.getText()); } }
還是很 easy 的嗷~
xml文件中結構類似這樣:
<?xml version="1.0" encoding="UTF-8"?> <books> <book id="001"> <title>Harry Potter</title> <author>J K. Rowling</author> </book> <book id="002"> <title>Learning XML</title> <author>Erik T. Ray</author> </book> </books>