操作带 命名空间的xml

来源:互联网 发布:塞班贝拉 淘宝 编辑:程序博客网 时间:2024/04/29 15:54
 <ah:AppHdr xmlns:ah="xxxxxxxxxxxxxxxxxxxxx">  
        <ah:as> 
            <ah:bb> 
                <ah:MmbId>ICL</ah:MmbId> 
          </ah:bb> 
        </ah:as>  

      </ah:AppHdr>  


如上报文,ah为命名空间,这种形式的报文用 dom4j 解析需要指定命名空间,不然会解析报错


map存在命名空间定义

Map<String, String>map=new HashMap<String, String>();  
map.put("ah","urn:iso:std:iso:20022:tech:xsd:head.001.001.01");  
map.put("doc","urn:iso:std:iso:20022:tech:xsd:pacs.008.001.06");  
map.put("fps","urn:hkicl:fps:xsd:fps.envelope.01");  

读取xml
SAXReader saxReader = new SAXReader();  
File file = new File("F:\\S001.xml");  
saxReader.getDocumentFactory().setXPathNamespaceURIs(map);
    Document doc = saxReader.read(file);  //这时生成的document就包含命名空间定义了


用xpath解析xml

List<Element> frEle = doc.selectNodes("//ah:Fr/ah:FIId/ah:FinInstnId/ah:ClrSysMmbId/ah:MmbId");
List<Element> toEle = doc.selectNodes("//ah:To/ah:FIId/ah:FinInstnId/ah:ClrSysMmbId/ah:MmbId");

得到元素再继续操作元素的值或者属性

原创粉丝点击