`
y150988451
  • 浏览: 195766 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

DOM解析

    博客分类:
  • XML
阅读更多
public class DOMTest{
        public static void main(String[] args) throws Exception{
        //第一步:创建解析器工厂
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        //第二步:File
        File file = new File("stud.xml");

        //第三步:file give to parser
        Document document = db.parse(file);
		
		//第四步:
		NodeList nodeList = document.getElementsByTagName("student");
        Node node = nodeList.item(1);

        NamedNodeMap map = node.getAttributes();
		//循环遍历
//        for (int i = 0; i < map.getLength(); i++) {
//            Attr attr = (Attr) map.item(i);
//            System.out.println(attr.getName() + "<<<<<<" + attr.getValue());
//        }
        //直接取值
        Attr attr = (Attr) map.getNamedItem("ID");
        System.out.println(attr.getValue());

        Node nameNode = node.getFirstChild();
        //两种方式:取节点里面的值
		//方式一:封装了方式二
        String str = nameNode.getTextContent();
        System.out.println(str);
        
		//方式二:最基本
        Node textNode = nameNode.getFirstChild();
        String str = textNode.getNodeValue();
        System.out.println("<<<<<<" + str);
		
		//---------------------------------------------------------------
		
		DOMTest t = new DOMTest();
        List<Student> list = t.parse(document);

        for (Student s : list) {
            System.out.println(s.getId() + "\t" + s.getName() + "\t" + s.getBirth());
        }
		//---------------------------------------------------------------
		
		Element e2 = document.getDocumentElement();
    	t.parse2(e2);
		//---------------------------------------------------------------
		
		Element e3 =document.getDocumentElement();
		t.parse3(e3);
		List<Student> list =t.getResult();
		for(Student s:list){
		   System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getBirth()+"\t");
		}
		
		}
		/**
		*有限次数的循环,如果很多层的话,要嵌套太多的for循环
		*/
		public List<Student> parse(Document document) throws Exception {
        List<Student> list = new ArrayList<Student>();
        NodeList nodeList = document.getElementsByTagName("student");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node studentNode = nodeList.item(i);
            Student s = new Student();
            NamedNodeMap map = studentNode.getAttributes();
            Attr attr = (Attr) map.getNamedItem("ID");
            s.setId(Long.parseLong(attr.getValue()));

            NodeList nodeList2 = studentNode.getChildNodes();
            for (int j = 0; j < nodeList2.getLength(); j++) {
                Node node = nodeList2.item(j);
                if ("name".equals(node.getNodeName())) {
                    String str = node.getTextContent();
                    s.setName(str);
                }
                if ("birth".equals(node.getNodeName())) {
                    String str = node.getTextContent();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    s.setBirth(sdf.parse(str));
                }
            }
            list.add(s);
        }
        return list;
		}
		
	   /**
		* 通过递归的方法遍历所有节点及其值,其属性
	   * @param e
	   */
        public void parse2(Element e){
	      System.out.println("节点的名字"+e.getNodeName());
	      if(e.hasAttributes()){
		   NamedNodeMap map =e.getAttributes();
		   for(int i=0;i<map.getLength();i++){
			   Attr attr =(Attr) map.item(i);
			   System.out.println("属性的名字是:"+attr.getName()+"属性的值:"+attr.getValue());
		   }
	     }
	     NodeList nodeList =e.getChildNodes();
		 for(int j=0;j<nodeList.getLength();j++){
		   Node node = nodeList.item(j);
		   if(node.getNodeType()==Node.ELEMENT_NODE){
			  parse2((Element)node);
		 }
		  if(node.getNodeType()==Node.TEXT_NODE){
			  String str = node.getNodeValue().trim();
			  if(str!=null&&str.length()>0){
				  System.out.println(str);
			  }
		  }
		}
      }
	  
	    /**
		 *用递归方式把xml值装载到Student对象中
		 */
	    private List<Student> list;
		private String flag;
		private Student s;

		public void parse3(Element el) throws ParseException {
			if ("students".equals(el.getNodeName())) {
				list = new ArrayList<Student>();
			}
			if ("student".equals(el.getNodeName())) {
				s = new Student();
				NamedNodeMap map = el.getAttributes();
				Attr attr = (Attr) map.getNamedItem("ID");
				s.setId(Long.parseLong(attr.getValue()));
				list.add(s);
			}
			if ("name".equals(el.getNodeName())) {
				flag = "name";
			}
			if ("birth".equals(el.getNodeName())) {
				flag = "birth";
			}
			NodeList nodeList = el.getChildNodes();
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node node = nodeList.item(i);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					parse3((Element) node);
				}
				if (node.getNodeType() == Node.TEXT_NODE) {
					String str = node.getNodeValue().trim();
					if (str != null && str.length() > 0 && "name".equals(flag))
						s.setName(str);
					if (str != null && str.length() > 0 && "birth".equals(flag)) {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						s.setBirth(sdf.parse(str));
					}

				}
				//
			}
		}

		public List<Student> getResult() {
			return this.list;
		}
}	
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics