Question

I ran into a problem while developing onto Blackberry. I am using KXML2 api for XML parsing (well actually, I got someone else's code to continue and fix, so I have to use this). The problem is the lack of cloning in java me, and im having some difficulities when trying to deep copy a node. (I dont want to go into details, but the point is, that i need to substitue data into specific points of a html and there is an xml describer for that) So..! :)

XMLElement childNode = node.getElement(ci);

This is the element I need to copy. XMLElement is a simple wrapper class, never mind that, it contains and Element attribute and some useful methods.

Now what I want is kind of like something like this :

XMLElement newChildNode = childNode.clone();

Since there is no cloning, no clonable interface in Java ME, I cannot do that, and this only creates a reference to the original element, which i need to preserve, while modifying the new element:

XMLElement newChildNode = childNode;

Can anyone come up with a usable idea about, how to create a deep copy of my childNode element? Thank you very much in advance!

Was it helpful?

Solution

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

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;
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top