首页 > 代码库 > XML解析——DOM

XML解析——DOM

 1 <?xml version="1.0" encoding="GBK"?> 2 <addresslist> 3     <linkman> 4         <name>李兴华</name> 5         <email>mldnqa@163.com</email> 6     </linkman> 7     <linkman> 8         <name>MLDN</name> 9         <email>mldnkf@163.com</email>10     </linkman>11 </addresslist>

 

 1 import java.io.* ; 2 import org.w3c.dom.* ; 3 import javax.xml.parsers.* ; 4 public class DOMDemo { 5     public static void main(String args[]) throws Exception { 6         // 取得DocumentBuilderFactory类的对象 7         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ; 8         // 取得DocumentBuilder类的对象 9         DocumentBuilder build = factory.newDocumentBuilder()  ;10         Document doc = build.parse(new File("D:" + File.separator + "dom_demo_01.xml")) ;11         // 得到所有的linkman节点12         NodeList nl = doc.getElementsByTagName("linkman") ;13         for(int x=0;x<nl.getLength();x++){14             Element e = (Element) nl.item(x) ;    // 取出每一个元素15             System.out.println("姓名:" + e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue()) ;16             System.out.println("邮箱:" + e.getElementsByTagName("email").item(0).getFirstChild().getNodeValue()) ;17         }18     }19 }

 

XML解析——DOM