[jdom-interest] copying element content
vonderLuft, Andrew
vonderluft.andrew at con-way.com
Fri Apr 5 15:04:17 PST 2002
Please forgive my ignorance, but surely there is a simple way to copy all
the content of one element to another, e.g.
oneElement.setContent(another.getContent());
However, this never works for me -- not sure why. It either hangs or gives
me "existing parent" errors. I've resorted to writing this utility method,
which, BTW, I submit for your use and/or abuse:
/**
* <p>
* <code>copyElementContent</code> copies content of source Element argument
* to destination Element argument, which is returned.
* Processes recursively to copy entire tree of child elements.
* </p>
* Creation date: (8/31/2001 1:44:07 PM)
* @author: Andrew vonderLuft
* @param: source org.jdom.Element - the source Element
* @param: dest org.jdom.Element - the destination Element
* @return: org.jdom.Element - the Element with copied content
*/
public static Element copyElementContent(Element source, Element dest) {
if (source == null) return null;
if (dest == null) dest = new Element(source.getName());
dest.removeChildren();
if (source.hasChildren()) {
List children = source.getChildren();
Element childSource, childDest;
for (int i=0; i < children.size(); i++) {
childSource = (Element) children.get(i);
childDest = new Element(childSource.getName());
dest.addContent(copyElementContent(childSource,
childDest));
}
} else {
if (source.getText().length() > 0)
dest.setText(source.getText());
}
List attrList = source.getAttributes();
if (attrList.size() > 0) {
for (int i = 0; i < attrList.size(); i++) {
dest.setAttribute( ((Attribute)
attrList.get(i)).detach());
}
}
return dest;
}
/**
* <mailto:vonderluft.andrew at con-way.com>
* Desk: 503.450.6055 Fax: 503.450.5790
* CON-WAY I.T. <www.con-way.com>
* @author: Andrew vonderLuft
*/
More information about the jdom-interest
mailing list