我在开发黑莓的时候遇到了一个问题。我正在使用XML进行KXML2解析(实际上,我得到了其他人的代码来继续进行修复,所以我必须使用这个)。问题是java me中缺少克隆,而我在尝试深度复制节点时遇到了一些困难。(我不想详述细节,但重点是,我需要将数据替换到html的特定点中,并且有一个xml描述符),所以..!:)
XMLElement childNode = node.getElement(ci);这是我需要复制的元素。XMLElement是一个简单的包装类,不要紧,它包含了元素属性和一些有用的方法。
现在我想要的东西是这样的:
XMLElement newChildNode = childNode.clone();因为在Java ME中没有克隆,没有可克隆的接口,所以我不能这样做,这只会创建对原始元素的引用,我需要在修改新元素时保留该引用:
XMLElement newChildNode = childNode;关于如何创建我的childNode元素的深层副本,有人能想出一个有用的想法吗?非常感谢您的提前!
发布于 2012-11-23 20:54:18
我设法用这个简单的实用函数解决了这个问题。它只是简单地迭代属性,复制它们,并在需要时递归地调用函数。
public static Element createClone(Element toClone) {
String namespace = (toClone.getNamespace() == null) ? "" : toClone.getNamespace();
String name = (toClone.getName() == null) ? "" : toClone.getName();
Element result = toClone.createElement(namespace, name);
int childCount = toClone.getChildCount();
int attributeCount = toClone.getAttributeCount();
for (int i = 0; i < attributeCount; i++) {
result.setAttribute(toClone.getAttributeNamespace(i), toClone.getAttributeName(i), toClone.getAttributeValue(i));
}
for (int j = 0; j < childCount; j ++) {
Object childObject = toClone.getChild(j);
int type = toClone.getType(j);
if (type == Node.ELEMENT) {
Element child = (Element) childObject;
result.addChild(Node.ELEMENT, createClone(child));
} else if (type == Node.TEXT) {
String childText = new String((String) childObject);
if (!childText.equals("")) {
result.addChild(Node.TEXT, childObject);
}
}
}
return result;
}https://stackoverflow.com/questions/12818009
复制相似问题