沈超琦的博客

STAY FOOLISH,STAY HUNGRY,STAY YOUNG!

  menu
8 文章
0 浏览
3 当前访客
ღゝ◡╹)ノ❤️

[原创]dom4j的指定element获取树结构

最近在做CDA文档(一种医疗机构内部通用的XML格式文档,基于V3模板)的项目,遇到了一个需求,通过指定CDA文档的xpath获取指定xml的树结构.

public List<Object> searchByNode(String documentId,String xpath){
	List resultList = new ArrayList<>();
	String cdacontent = xxxService.getByDocumentId(documentId)
	.....通过documentId 获取具体的CDA文档
	Map map = new HashMap();
	map.put("cda","urn:hl7-org:v3"); //指定XML命名空间
	SAXReader reader = new SAXReader();
	reader.getDocumentFactory().setXPathNamespaceURIs(map);
	Ducument result = null;
	InputSource source = new InputSource(new StringReader(cdacontent));
	result = reader.read(source);
	List<Element> list = result.selectNodes(xpath)
	for(Element e : List){
		Map<String,Object> ele = generateXml(e);
		resultList.add(ele);
	}
	return resultList;
} 

public Map<String, Object> generateXml(Element element) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String textTrim = element.getTextTrim();
        result.put("text", textTrim);
        //处理属性
        Map<String, Object> attribute = new HashMap<>();
        List<Attribute> attributeList = element.attributes();
        for (Attribute attr : attributeList) {
            attribute.put(attr.getName(), attr.getValue());
        }
        result.put("attribute", attribute);
        //标签名
        result.put("label", element.getName());
        //子节点
        List<Map<String, Object>> childrenList = new ArrayList<>();
        List<Element> elementList = element.elements();
        for (Element ele : elementList) {
            Map<String, Object> child = generateXml(ele); //递归调用
            childrenList.add(child);
        }
        result.put("children", childrenList);
        return result;
    }

标题:[原创]dom4j的指定element获取树结构
作者:shark
地址:https://www.linkjb.com/articles/2020/05/22/1590119203338.html