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; /** * 遍歷xml所有節點(包括子節點下還有子節點多層嵌套) */ public class TestXML { public static void main(final String[] args) { final TestXML test = new TestXML(); try { test.testGetRoot(); } catch (final Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 獲取文件的xml對象,然后獲取對應的根節點root */ public void testGetRoot() throws Exception { final SAXReader sax = new SAXReader();// 創建一個SAXReader對象 final File xmlFile = new File("C:\\Users\\.yang\\Desktop\\ss.xml");// 根據指定的路徑創建file對象 final Document document = sax.read(xmlFile);// 獲取document對象,如果文檔無節點,則會拋出Exception提前結束 final Element root = document.getRootElement();// 獲取根節點 getNodes(root);// 從根節點開始遍歷所有節點 } /** * 從指定節點Element node開始,遞歸遍歷其所有子節點 */ public void getNodes(final Element node) { System.out.println("-------開始新節點-------------"); // 當前節點的名稱、文本內容和屬性 System.out.println("當前節點名稱:" + node.getName());// 當前節點名稱 System.out.println("當前節點的內容:" + node.getTextTrim());// 當前節點內容 final List<Attribute> listAttr = node.attributes();// 當前節點的所有屬性 for (final Attribute attr : listAttr) {// 遍歷當前節點的所有屬性 final String name = attr.getName();// 屬性名稱 final String value = attr.getValue();// 屬性的值 System.out.println("屬性名稱:" + name + "---->屬性值:" + value); } // 遞歸遍歷當前節點所有的子節點 final List<Element> listElement = node.elements();// 所有一級子節點的list for (final Element e : listElement) {// 遍歷所有一級子節點 getNodes(e);// 遞歸 } } }
參考文章:https://blog.csdn.net/sidihuo/article/details/47318723
