java自带dom工具使用实例

代码参考自

黄亿华大神的<<1000行代码读懂Spring(一)- 实现一个基本的IoC容器>>
原网页如下
http://my.oschina.net/flashsword/blog/192551

package com.myspring;   
  
import java.io.FileInputStream;   
import java.io.InputStream;   
  
import javax.xml.parsers.DocumentBuilder;   
import javax.xml.parsers.DocumentBuilderFactory;   
  
import org.w3c.dom.Document;   
import org.w3c.dom.Element;   
import org.w3c.dom.Node;   
import org.w3c.dom.NodeList;   
  
public class XmlReader {   
    public static void main(String[] args) {   
        new XmlReader();   
    }   
    public XmlReader(){   
        DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();   
        try {   
            DocumentBuilder domBuilder = domfac.newDocumentBuilder();   
            
            //默认是工程目录
            InputStream is =new FileInputStream("bin/resources/tinyioc.xml");   
            Document doc = domBuilder.parse(is);   
            Element root = doc.getDocumentElement();   
            NodeList beans = root.getChildNodes();   
            if(beans!=null) 
                for (int i = 0; i < beans.getLength(); i++) {
                	Node bean =  beans.item(i);   
                    if (bean.getNodeName().equals("bean")) {
                    	Element el=(Element) bean;
                    	System.out.println( el.getAttribute("id") +"  "+el.getAttribute("class") );
                    	NodeList propertyNode = el.getElementsByTagName("property");
                    	for (int j = 0; j < propertyNode.getLength(); j++) 
                    		if(propertyNode.item(j) instanceof Element){
                    			Element e=(Element) propertyNode.item(j);
                    			String name=e.getAttribute("name");
                    			String value=e.getAttribute("value").equals("")?e.getAttribute("ref"):e.getAttribute("value");
                    			System.out.println("       "+name+"  "+value );
                    		}	
						
					}
                    
  
                }   
               
        } catch (Exception e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        }   
           
    }   
}  
xml如下






    
        
        
    
        
    
    

    

    

    
        
        
    


运行结果如下

helloWorldService  com.myspring.HelloWorldServiceImpl
       text  Hello World!
       out  outputService
outputService  com.myspring.OutputService
autoProxyCreator  us.codecraft.tinyioc.aop.AspectJAwareAdvisorAutoProxyCreator
timeInterceptor  us.codecraft.tinyioc.aop.TimerInterceptor
aspectjAspect  us.codecraft.tinyioc.aop.AspectJExpressionPointcutAdvisor
       advice  timeInterceptor
       expression  execution(* us.codecraft.tinyioc.*.*(..))





你可能感兴趣的:(java自带dom工具使用实例)