xml文件持久化之后还原

上一篇文章是xml文件的解析和持久化,今天是关于xml文件的还原,也就是当将xml文件按照标签属性等等元素给它解体之后,我们要是想还原回原来的文件要进行的操作,话不多说,直接上代码:

所有用到的类和依赖,在上篇文章都有粘贴哦:

这个fileId要作为参数输入,依据这个fileId去查询当初存入数据库中的关于xml文件的标签id们

@Transactional(rollbackFor = Exception.class)
   List<XmlTagInfoEntity> xmlEntityList = xmlTagInfoDao.queryList(fileId);
        List<Long> parentIdList =new ArrayList<>();
        for (XmlTagInfoEntity xmlTagInfoEntity : xmlEntityList) {
            if("01".equals(xmlTagInfoEntity.getIfAttribute())){
                parentIdList.add(xmlTagInfoEntity.getTagId());
            }
        }
        List<XmlAttributeInfoEntity> attributeEntityList=xmlAttributeInfoDao.queryAllAttribute(fileId);
        //生成属性集合
        Map<Long, List<Map<String, String>>> attributeMap = new HashedMap();
        List<Map<String, String>> attributeList = null;
        int j=0;
        for (Long id : parentIdList) {
            attributeList = new ArrayList<>();
            for (int i=j; i < attributeEntityList.size(); i++) {
                if (attributeEntityList.get(i).getTagId().longValue() == id.longValue()) {
                    Map<String, String> attribute = new HashedMap();
                    attribute.put("name", attributeEntityList.get(i).getAttributeName());
                    attribute.put("value", attributeEntityList.get(i).getAttributeValue());
                    attributeList.add(attribute);
                    j++;
                }
            }
            attributeMap.put(id, attributeList);
        }
        Document doc = DocumentHelper.createDocument();
        XmlTagInfoEntity xmlEntity = xmlEntityList.get(0);
        //根标签
        Element firstEle = doc.addElement(xmlEntity.getQualifiedName());
        //namespace
        String namespace1 = xmlEntity.getNameSpace1();
        String[] xmlns = new String[2];
        if (namespace1 != null && !"".equals(namespace1)) {
            xmlns = namespace1.split("=");
            firstEle = firstEle.addNamespace("", xmlns[1]);
        }
        String namespace2 = xmlEntity.getNameSpace2();
        if (namespace2 != null && !"".equals(namespace2)) {
            List<String> xmlns2 = Arrays.asList(namespace2.split("\\|"));
            for (String s : xmlns2) {
                String[] xmlns2arr = s.split("=");
                Namespace namespace = new Namespace(xmlns2arr[0], xmlns2arr[1]);
                firstEle.add(namespace);
            }
        }
        //添加属性
        if (xmlEntity.getIfAttribute().equals("01")) {
            List<Map<String, String>> attributes = attributeMap.get(xmlEntity.getTagId());
            for (Map<String, String> attribute : attributes) {
                System.out.println(attribute.get("value").isEmpty());
                firstEle.addAttribute(attribute.get("name"), attribute.get("value"));
            }
        }
        xmlEntityList.remove(xmlEntity);
        LinkedHashMap<String, Object> nodeMap = new LinkedHashMap();
        List<Object> nodeList = new ArrayList<>();
        nodeList.add(xmlEntity.getTagId() + "");
        nodeList.add(firstEle);
        nodeList.add(xmlns[1]);
        nodeMap.put(xmlEntity.getTagId() + "", nodeList);
        List<XmlTagInfoEntity> xmlEntitie = new ArrayList<>();
        for (int i = 0; i < xmlEntityList.size(); i++) {
            xmlEntitie.add(xmlEntityList.get(i));
            if (xmlEntitie.size() > 1000) {
                AddChildNode(nodeMap, xmlEntitie, null, firstEle, xmlEntity.getTagId() + "", xmlns[1], attributeMap);
                xmlEntitie = new ArrayList<>();
            }
        }
        if (xmlEntitie.size() > 0) {
            AddChildNode(nodeMap, xmlEntitie, null, firstEle, xmlEntity.getTagId() + "", xmlns[1], attributeMap);
        }
        try {
            recover(doc, fileEncoding, contentEncode);
        } catch (IOException e) {
            LOGGER.error("xml还原转换异常");
            return false;
        }
        return true;

查出数据库中关于指定xml文件的所有内容,标签信息存入list,属性信息存入attributeMap,还有一个nodeMap用来去重的

private void AddChildNode(LinkedHashMap<String, Object> nodeMap, List<XmlTagInfoEntity> list, Element parentele, Element items, String id, String parxmlns, Map<Long, List<Map<String, String>>> attributeMap) {
        for (int i = 0; i < list.size(); i++) {
            List<Object> nodeList = new ArrayList<>();
            XmlTagInfoEntity node = list.get(i);
            if (node.getParentTagId().toString().equals(id)) {
                String namespace1 = node.getNameSpace1();
                Element item = null;
                //添加namespace
                if (namespace1 != null && !"".equals(namespace1)) {
                    item = items.addElement(node.getQualifiedName(), namespace1);
                } else if (parxmlns != null) {
                    item = items.addElement(node.getQualifiedName(), parxmlns);
                } else {
                    item = items.addElement(node.getQualifiedName());
                }
                namespace1 = parxmlns;
                //添加标签内容
                String text = node.getTagContent();
                if (text != null && !text.replaceAll("\n|\r| ", "").isEmpty()) {
                    item.setText(text);
                }
                //添加属性
                if (node.getIfAttribute().equals("01")) {
                    List<Map<String, String>> attributes = attributeMap.get(node.getTagId());
                    for (Map<String, String> attribute : attributes) {
                        item.addAttribute(attribute.get("name"), attribute.get("value"));
                    }
                }
                nodeList.add(node.getTagId() + "");
                nodeList.add(item);
                nodeList.add(namespace1);
                nodeMap.put(node.getTagId() + "", nodeList);
                List newList = new ArrayList();
                for (XmlTagInfoEntity entity : list) {
                    if (!list.get(i).getTagId().toString().equals(entity.getTagId().toString())) {
                        newList.add(entity);
                    }
                }
                list = new ArrayList<>();
                list.addAll(newList);
                i--;
                if (list.size() == 0) {
                    break;
                }
            } else {
                Set<Map.Entry<String, Object>> set = nodeMap.entrySet();
                Iterator<Map.Entry<String, Object>> iterator = set.iterator();
                while (iterator.hasNext()) {
                    Map.Entry entry = iterator.next();
                    id = (String) entry.getKey();
                    if (id.equals(node.getParentTagId() + "")) {
                        List<Object> nodeMsg = (List<Object>) entry.getValue();
                        items = (Element) nodeMsg.get(1);
                        parxmlns = (String) nodeMsg.get(2);
                        AddChildNode(nodeMap, list, null, items, id, parxmlns, attributeMap);
                        list = new ArrayList<>();
                        break;
                    }
                }
            }
        }
    }

调用这个方法的时候说明已经把xml文件都还原成docoment了,剩下的就是输出存到指定目录了

  public void recover(Document doc,String fileEncoding) throws IOException {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(fileEncoding);
        File file = new File("f:test\\xml\\big.xml");
        //生成XMLWriter对象,构造函数中的参数为需要输出的文件流和格式
        XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
        writer.write(doc);
    }

到这里,代码部分就结束了,因为有时候我在网上查找资料的时候,偶尔会因为不知道依赖引入哪个,费时间去找依赖,所以这里就把用到的依赖也粘贴在这里了

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.collections.map.HashedMap;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.*;

结束啦,结束啦,希望大家指出不足,我多多改正,感谢感谢

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值