问题描述
我有一个方法应该使用已经在文件上运行其他一些方法的 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% 的运行时间实现了相同的结果。