微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java DOM XML 编辑 - 添加和删除元素非常慢

如何解决Java DOM XML 编辑 - 添加和删除元素非常慢

我有一个方法应该使用已经在文件上运行其他一些方法的 DOM 编辑器将行更改为我的 svg (xml) 文档中的路径。但是,使用这个新的 linetoPath() 方法,我已经在需要编辑的文件大小上运行了几次(> 63,000 行需要更改为路径),运行时间为 3 到 4 分钟。

public void linetoPath() {
        NodeList nList = doc.getElementsByTagName("line");
        System.out.println("nList length = " + nList.getLength());
        
        String x1,x2,y1,y2,draw;
        int len = nList.getLength();
        for (int i = 0; i < len; i++){
            // we have to keep editing the 1st element,because the
            // prevIoUsly-first element is removed from this list at
            // the end of the function
            Element line = (Element) nList.item(0);
            
            // turn x & y attributes of line into draw instructions
            // for the path
            x1 = (line.getAttribute("x1"));
            x2 = (line.getAttribute("x2"));
            y1 = (line.getAttribute("y1"));
            y2 = (line.getAttribute("y2"));
            draw = "M" + x1 + " " + y1 + ",L" + x2 + " " + y2;
            
            Element path = doc.createElement("path");
            path.setAttribute("d",draw);
            
            // copy over all other attributes except x & y values
            NamednodeMap listAttrs = line.getAttributes();
            for (int j = 0; j < listAttrs.getLength(); j++) {
                Attr attr = (Attr) listAttrs.item(j);
                char attrFirstChar = attr.getNodeName().charat(0);
                
                if (attrFirstChar != 'x' && attrFirstChar != 'y'){
                    //path.setAttributeNode(attr);
                    path.setAttribute(attr.getName(),attr.getValue());
                }
            }
            //System.out.println("Path " + i + " ready to write");
            
            // replace the line with our new path
            line.getParentNode().appendChild(path);
            line.getParentNode().removeChild(line);
            //System.out.println("***replaced line " + i + " with path");
        }
    }

当我注释掉 line.getParentNode().appendChild(path);line.getParentNode().removeChild(line); 时 - 即当我完成创建新路径的所有工作但实际上没有替换该行的路径时 - 我的运行时间下降到 3 秒。

我曾尝试将这两行折叠成一个 replaceChild() 行,但这会使我的运行时间超过 6 分钟来编辑这个单个文档。

有没有什么方法可以使用 DOM 编辑器更快地做到这一点?

[另外:我有点新,所以对我的代码布局或可读性的任何其他批评将不胜感激]

解决方法

迄今为止我发现的最佳解决方案是完全忽略 DOM 编辑器。似乎没有一种方法可以在不占用太长时间的情况下使用它。

使用 BufferedReader 获取每一行,在行中执行大量手动字符串搜索和子字符串连接和字符串插入,然后使用 BufferedWriter 写出新行,以不到 5% 的运行时间实现了相同的结果。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?