对含有命名空间的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();
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值