`

对含有命名空间的xml进行解析

阅读更多
这是网上一个人模拟spring IOC 加载xml部分的代码,
作者使用的saxReader进行解析的xml的。对于逐步(顺序)进行解析xml,saxReader是一种比较好的选择。
private void readXML(String filename) {  
           SAXReader saxReader = new SAXReader();     
            Document document=null;     
            try{  
             URL xmlpath = this.getClass().getClassLoader().getResource(filename); //通过classLoader实例的getResource获取classPath下的filename文件的URL。 
             document = saxReader.read(xmlpath); //saxReader通过一个URL读取xml到documnet中。 
//因为xml是带有命名空间的,所以需要设置查询路径,然后通过查询路径的selectNodes(查找范围的节点)获取想要遍历的List<element>集合。
             Map<String,String> nsMap = new HashMap<String,String>();  
             nsMap.put("ns","http://www.springframework.org/schema/beans");//设置命名空间变量  
             XPath xsub = document.createXPath("//ns:beans/ns:bean");
// 两个反斜杠代表从根上开始,创建beans/bean查询路径  
             xsub.setNamespaceURIs(nsMap);//设置命名空间  
             List<Element> beans = xsub.selectNodes(document);//获取文档下所有bean节点   
             for(Element element: beans){  
                String id = element.attributeValue("id");//获取id属性值  
                String clazz = element.attributeValue("class"); //获取class属性值          
                Definition beanDefine = new Definition(id, clazz);  
                XPath propertysub =  element.createXPath("ns:property"); 
//获取命名空间下的property的查询路径
                propertysub.setNamespaceURIs(nsMap);//设置命名空间  
                List<Element> propertys = propertysub.selectNodes(element);  
                for(Element property : propertys){                    
                    String propertyName = property.attributeValue("name");//元素内部引用的属性也获取  
                    String propertyref = property.attributeValue("ref");  
                    ProsDefinition propertyDefinition = new ProsDefinition(propertyName, propertyref);  
                    beanDefine.getPropertys().add(propertyDefinition);  
                }  
                beanDefines.add(beanDefine);  
             }   
            }catch(Exception e){     
                e.printStackTrace();  
            }  
    }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics