1 56 57 package org.jdom.contrib.ids; 58 59 import java.util.*; 60 61 import org.jdom.Attribute; 62 import org.jdom.Content; 63 import org.jdom.Document; 64 import org.jdom.Element; 65 import org.jdom.Parent; 66 import org.jdom.Namespace; 67 68 75 public class IdElement extends Element { 76 77 79 public IdElement(String name, Namespace namespace) { 80 super(name, namespace); 81 } 82 83 public IdElement(String name) { 84 this(name, (Namespace)null); 85 } 86 87 public IdElement(String name, String uri) { 88 this(name, Namespace.getNamespace("", uri)); 89 } 90 91 public IdElement(String name, String prefix, String uri) { 92 this(name, Namespace.getNamespace(prefix, uri)); 93 } 94 95 protected Content setParent(Parent parent) { 96 Document prevDoc = this.getDocument(); 98 Document newDoc = (parent != null)? parent.getDocument(): null; 99 100 super.setParent(parent); 102 103 if (newDoc != prevDoc) { 104 transferIds(prevDoc, newDoc); 109 } 110 return this; 111 } 112 113 114 128 private void transferIds(Document prevDoc, Document newDoc) 129 { 130 if ((prevDoc instanceof IdDocument) || (newDoc instanceof IdDocument)) { 131 Map ids = getIds(this, new HashMap()); 134 135 if (prevDoc instanceof IdDocument) { 137 IdDocument idDoc = (IdDocument)prevDoc; 140 141 for (Iterator i=ids.keySet().iterator(); i.hasNext(); ) { 142 idDoc.removeId(i.next().toString()); 143 } 144 } 145 147 if (newDoc instanceof IdDocument) { 149 IdDocument idDoc = (IdDocument)newDoc; 152 153 for (Iterator i=ids.keySet().iterator(); i.hasNext(); ) { 154 String key = i.next().toString(); 155 idDoc.addId(key, (Element)(ids.get(key))); 156 } 157 } 158 } 160 return; 163 } 164 165 177 private static Map getIds(Element root, Map ids) { 178 addIdAttributes(root, ids); 179 180 List children = root.getContent(); 181 for (Iterator i=children.iterator(); i.hasNext(); ) { 182 Object o = i.next(); 183 if (o instanceof Element) { 184 getIds((Element)o, ids); 185 } 186 } 187 return ids; 188 } 189 190 199 private static void addIdAttributes(Element elt, Map ids) { 200 List attrs = elt.getAttributes(); 201 for (Iterator i=attrs.iterator(); i.hasNext(); ) { 202 Attribute attr = (Attribute)(i.next()); 203 204 if (attr.getAttributeType() == Attribute.ID_TYPE) { 205 ids.put(attr.getValue(), elt); 206 break; 207 } 208 } 209 return; 210 } 211 } 212 213 | Popular Tags |