xml結構java
<?xml version="1.0" encoding="UTF-8"?> <sites> <site host="sina.com.cn" name="新浪網" charset="utf-8"> <news> <collectionUid>2</collectionUid> <mediaType>新聞門戶</mediaType> </news> <blog> <collectionUid>63</collectionUid> <mediaType>博客</mediaType> </blog> </site> <site host="qq.com" name="騰訊" charset="gb2312"> <news> <collectionUid>1</collectionUid> <mediaType>新聞</mediaType> </news> <blog> </blog> </site> </sites>
解析方法code
public class Dom4JParserXml { @SuppressWarnings("unchecked") public static void parseXml() throws FileNotFoundException, DocumentException { Document doc = new SAXReader().read(Dom4JParserXml.class.getResourceAsStream("/sites-config.xml")); List itemList = doc.selectNodes("/sites/site"); Iterator it = itemList.iterator(); while (it.hasNext()) { Element element = (Element) it.next(); parseEle(element); } } private static void parseEle(Element el) { try { String name = el.attributeValue("name"); System.out.println("------->>"+name); Element elNew = el.element("news"); Element elblog = el.element("blog"); if(elNew != null && elNew.elements().size() > 0) { String collectionUid = elNew.elementText("collectionUid"); String mediaType = elNew.elementText("mediaType"); System.out.println("-------new:collectionUid>>"+collectionUid); System.out.println("-------new:mediaType>>"+mediaType); } if(elblog != null && elblog.elements().size() > 0) { String collectionUid = elblog.elementText("collectionUid"); String mediaType = elblog.elementText("mediaType"); System.out.println("-------blog:collectionUid>>"+collectionUid); System.out.println("-------blog:mediaType>>"+mediaType); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String [] args) { try { parseXml(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } } }
解析結果:控制檯輸出xml
------->>新浪網 -------new:collectionUid>>2 -------new:mediaType>>新聞門戶 -------blog:collectionUid>>63 -------blog:mediaType>>博客 ------->>騰訊 -------new:collectionUid>>1 -------new:mediaType>>新聞 ------->>網易 -------new:collectionUid>>3 -------new:mediaType>>新聞 ------->>搜狐 -------new:collectionUid>>4 -------new:mediaType>>新聞