01: package org.ontoware.aifbcommons.xml;
02:
03: import java.util.List;
04: import java.util.Map;
05:
06: import org.dom4j.Document;
07: import org.dom4j.DocumentHelper;
08: import org.dom4j.Element;
09:
10: public class DocumentComposer {
11:
12: public static final String ELEMENT_REPLACE = "replace";
13: public static final String ATTRIBUTE_KEY = "key";
14:
15: /**
16: *
17: * @param master an XML document with <replace key="..."> elements
18: * @param content - a ampping from replacement keys to XML documents
19: * @return the master documents with all <replace>-elements replaced by
20: * the correcponding document form the 'content' mapping *
21: */
22: @SuppressWarnings("unchecked")
23: public static Document compose(Document master,
24: Map<String, Document> content) {
25: Document result = DocumentHelper.createDocument();
26: result.add(master.getRootElement().createCopy());
27: List list = result.selectNodes("//replace");
28:
29: for (Object o : list) {
30: Element e = (Element) o;
31: String key = e.attribute("key").getStringValue();
32: Document d = content.get(key);
33: Element root = d.getRootElement();
34: root.detach();
35: Element target = e.getParent();
36: List targetContent = target.content();
37: int i = target.indexOf(e);
38: targetContent.remove(i);
39: targetContent.add(i, root);
40: target.setContent(targetContent);
41: }
42:
43: return result;
44: }
45:
46: }
|