DOM解析xml

来源:互联网 发布:蜂蜜和四叶草 知乎 编辑:程序博客网 时间:2024/06/06 09:35

 

  1. package DOM;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.xml.parsers.DocumentBuilder;
  6. import javax.xml.parsers.DocumentBuilderFactory;
  7. import javax.xml.parsers.ParserConfigurationException;
  8.  
  9. import org.w3c.dom.Document;
  10. import org.w3c.dom.NamedNodeMap;
  11. import org.w3c.dom.Node;
  12. import org.w3c.dom.NodeList;
  13. import org.xml.sax.SAXException;
  14.  
  15. public class DOMTest {
  16.  
  17. public static void main(String[] args{
  18. //通过DocumentBuilderFactory.newInstance()创建DocumentBuilderFactory对象
  19. DocumentBuilderFactory dbf DocumentBuilderFactory.newInstance();
  20.  
  21. try {
  22. //创建DocmentBuilder对象
  23. DocumentBuilder db dbf.newDocumentBuilder();
  24. //通过DocmentBuilder对象的parse方法加载books.xml文件到当前项目下
  25.     Document d  db.parse("books.xml");
  26.     //获取book的所有节点
  27.     NodeList bookList d.getElementsByTagName_r("book");
  28.     //通过getLength()方法获取节点长度
  29.     System.out.println("共有"bookList.getLength()+ "本书");
  30.     for (int i0; ibookList.getLength(); i++){
  31.     //通过item(i)方法获取一个book节点,nodelist的索引值从0开始
  32.     Node book bookList.item(i);
  33.     //获取book节点的属性集合
  34.     NamedNodeMap attrs  book.getAttributes();
  35.     System.out.println("第"(i+1) "共有" attrs.getLength() +"个属性");
  36.     for(int j =0;jattrs.getLength();j++){
  37.     Node attr  attrs.item(j);
  38.     System.out.print("属性名:"+attr.getNodeName());  
  39.     System.out.println(",属性值:"attr.getNodeValue());
  40.     }
  41.     NodeList b  book.getChildNodes();
  42.     System.out.println("第"i +"本书共有" +b.getLength()+ "个节点");
  43.     for (int j 0;jb.getLength();j++){
  44.     if(b.item(j).getNodeType()== Node.ELEMENT_NODE ){
  45.     System.out.println(b.item(j).getNodeName());
  46.     }
  47.     
  48.     }
  49.     
  50.     }
  51.     
  52.     
  53.     
  54. catch (IOException e{
  55.  
  56. e.printStackTrace();
  57. }
  58.     catch (ParserConfigurationException e{
  59.  
  60.     e.printStackTrace();
  61.     }
  62.     catch (SAXException e{
  63.  
  64.     e.printStackTrace();
  65.     
  66.  
  67.  
  68.  
  69. }
  70.  
  71. }
  72.  
0 0
原创粉丝点击