Deep copy node with kxml (java me)

I ran into a problem developing on Blackberry. I use the KXML2 api for parsing XML (well, actually, I got another user's code to continue and fix, so I have to use this). The problem is the lack of cloning in java me, and I am having some difficulties when trying to deep copy the node. (I don’t want to go into details, but the fact is that I need to substitute data at certain html points, and for this there is an xml descriptor) So ..! :)

XMLElement childNode = node.getElement(ci); 

This is the item I need to copy. XMLElement is a simple wrapper class, it doesn't matter, it contains the Element attribute and some useful methods.

Now what I want looks like something like this:

 XMLElement newChildNode = childNode.clone(); 

Since there is no cloning in Java ME, there is no cloned interface, I cannot do this, and this only creates a link to the original element that I need to save by changing the new element:

 XMLElement newChildNode = childNode; 

Can anyone come up with a useful idea on how to create a deep copy of my childNode element? Thank you so much in advance!

+4
source share
1 answer

I was able to solve the problem with this simple utility. It simply iterates through the attributes, copies them, and calls the function recursively, if necessary.

 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; } 
+1
source

Source: https://habr.com/ru/post/1438868/


All Articles