java基础之dom4j解析带命名空间的xml文件

在项目开发时,由于某种原因,需要解析返回的xml格式的字符串,读取里面某个带命名空间的属性及其值重新写到实体类去,在众多开源工具中,我选择了dom4j,觉得使用起来比较方便,其他工具就较少使用。

针对带命名空间的xml,想获取某命名空间下的属性,就先必须重新设置Document工厂的PathNamespaceUrl,示例如下:

//maven包
 <!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
          <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
          </dependency>

          <!-- https://mvnrepository.com/artifact/jaxen/jaxen -->
          <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
          </dependency>
//http://www.opengis.net/wmts/1.0和
//http://www.opengis.net/ows/1.1是分别ns、ows的命名空间缩写
//故应把两者写到Map,再设置到PathNamespaceURIs
//new DocumentFactory(),每次主动实例一个Document工厂,防止第二次引用时会出现寻找不到map,
//不主动new new DocumentFactory(),是用单例模式,才会出现寻找不到命名空间map的错误
 Map map = new HashMap();
            map.put("mo", "http://www.xxx.com/dasd/1.0");
            map.put("os", "http://www.xxxx.net/dasd/1.1");
            SAXReader saxReader = new SAXReader(new DocumentFactory());
            saxReader.getDocumentFactory().setXPathNamespaceURIs(map);
            Document document = null;
            try {
                document = saxReader.read(inputStream);//inputStream是指某一种流,可能是文件流、网络流
            } catch (DocumentException e) {
                e.printStackTrace();
            }

其实命名空间就是如spring.xml文件里面的最上面那些:

xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xmlns:aop="http://www.springframework.org/schema/aop"  
       xmlns:tx="http://www.springframework.org/schema/tx"  

你即可把http://www.w3.org/2001/XMLSchema-instance写入map:

Map map=new HashMap();
map.put("xsi","http://www.w3.org/2001/XMLSchema-instance");

接下来就是根据需要获取xml文件中相应属性:

 String topLeftCorner = document.selectSingleNode("//mo:TopLeftCorner").getText();
 String tileMatrixSet = document.selectSingleNode("//os:TileMatrixSet").getText();
 String layerName = document.selectSingleNode("//os:Title").getText();

更多的操作方法可仔细查看Document对象里面的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值