1 7 8 package org.dom4j.io; 9 10 import org.dom4j.Document; 11 import org.dom4j.Element; 12 import org.dom4j.ElementHandler; 13 import org.dom4j.ElementPath; 14 15 28 class SAXModifyElementHandler implements ElementHandler { 29 private ElementModifier elemModifier; 30 31 private Element modifiedElement; 32 33 public SAXModifyElementHandler(ElementModifier elemModifier) { 34 this.elemModifier = elemModifier; 35 } 36 37 public void onStart(ElementPath elementPath) { 38 this.modifiedElement = elementPath.getCurrent(); 39 } 40 41 public void onEnd(ElementPath elementPath) { 42 try { 43 Element origElement = elementPath.getCurrent(); 44 Element currentParent = origElement.getParent(); 45 46 if (currentParent != null) { 47 Element clonedElem = (Element) origElement.clone(); 49 50 modifiedElement = elemModifier.modifyElement(clonedElem); 52 53 if (modifiedElement != null) { 54 modifiedElement.setParent(origElement.getParent()); 56 modifiedElement.setDocument(origElement.getDocument()); 57 58 int contentIndex = currentParent.indexOf(origElement); 60 currentParent.content().set(contentIndex, modifiedElement); 61 } 62 63 origElement.detach(); 65 } else { 66 if (origElement.isRootElement()) { 67 Element clonedElem = (Element) origElement.clone(); 69 70 modifiedElement = elemModifier.modifyElement(clonedElem); 72 73 if (modifiedElement != null) { 74 modifiedElement.setDocument(origElement.getDocument()); 76 77 Document doc = origElement.getDocument(); 79 doc.setRootElement(modifiedElement); 80 } 81 82 origElement.detach(); 84 } 85 } 86 87 if (elementPath instanceof ElementStack) { 90 ElementStack elementStack = ((ElementStack) elementPath); 91 elementStack.popElement(); 92 elementStack.pushElement(modifiedElement); 93 } 94 } catch (Exception ex) { 95 throw new SAXModifyException(ex); 96 } 97 } 98 99 104 protected Element getModifiedElement() { 105 return modifiedElement; 106 } 107 } 108 109 145 | Popular Tags |