练习之XML读取

作者:源码世界时间:2014-03-13分类:程序员碎语评论:0浏览:6128
        /**
         * 读取XML使用jdom-2.0.5.jar,其中Node为自己封装的
         */   
        public Node parseXml(final String fileName) throws ParseXmlException, 
		NullPointerException, IllegalArgumentException {
		
		if(fileName == null) {
			
			throw new NullPointerException("解析XML文件名空指针异常");
		}
		
		SAXBuilder saxBuilder = null;
		Document document = null;
		Element rootElmt = null;
		Node node = null;
		
		try {
			
			saxBuilder = new SAXBuilder();
			document = saxBuilder.build(fileName);
			rootElmt = document.getRootElement();
			node = parseNode(rootElmt);
		} catch (JDOMException e) {
			throw new ParseXmlException(e.getMessage());
		} catch (IOException e) {
			throw new ParseXmlException(e.getMessage());
		}
		
		return node;
	}
	
	public Node parseNode(Element element) throws IllegalArgumentException {
		
		if(element == null) {
			
			return null;
		}
		
		Node node = new Node(element.getName(), element.getText());
		
		for(Attribute attr : element.getAttributes()) {
			
			node.add(attr.getName(), attr.getValue());
		}
		
		for(Element child : element.getChildren()) {
			
			node.addChild(parseNode(child));
		}
		
		return node;
	}
标签:Java  
返回顶部
分享按钮