1 24 package org.riotfamily.forms.support; 25 26 import org.riotfamily.common.beans.ObjectWrapper; 27 import org.riotfamily.common.xml.XmlUtils; 28 import org.springframework.beans.AbstractPropertyAccessor; 29 import org.springframework.beans.BeansException; 30 import org.springframework.util.xml.DomUtils; 31 import org.w3c.dom.Element ; 32 import org.w3c.dom.Node ; 33 34 public class XmlElementWrapper extends AbstractPropertyAccessor 35 implements ObjectWrapper { 36 37 private static final String ATTRIBUTE_PREFIX = "@"; 38 39 private static final String TEXT_VALUE = "text()"; 40 41 public Element element; 42 43 private String elementName; 44 45 46 public XmlElementWrapper(String elementName) { 47 this.elementName = elementName; 48 } 49 50 public Class getObjectClass() { 51 return Element .class; 52 } 53 54 public void setObject(Object object) { 55 if (object != null) { 56 element = (Element ) object; 57 } 58 else { 59 element = XmlUtils.createDocument().createElement(elementName); 60 } 61 } 62 63 public Object getObject() { 64 return element; 65 } 66 67 public Object getPropertyValue(String name) throws BeansException { 68 if (element == null) { 69 return null; 70 } 71 if (name.startsWith(ATTRIBUTE_PREFIX)) { 72 return element.getAttribute(name.substring(1)); 73 } 74 if (name.equals(TEXT_VALUE)) { 75 return DomUtils.getTextValue(element); 76 } 77 Element child = XmlUtils.getFirstChildByTagName(element, name); 78 return child != null ? DomUtils.getTextValue(child) : null; 79 } 80 81 public void setPropertyValue(String name, Object value) throws BeansException { 82 if (element == null) { 83 element = XmlUtils.createDocument().createElement(elementName); 84 } 85 if (name.startsWith(ATTRIBUTE_PREFIX)) { 86 if (value != null) { 87 element.setAttribute(name.substring(1), value.toString()); 88 } 89 else { 90 element.removeAttribute(name); 91 } 92 } 93 else if (name.equals(TEXT_VALUE)) { 94 XmlUtils.setTextValue(element, value.toString()); 95 } 96 if (value instanceof Element ) { 97 Element child = XmlUtils.getFirstChildByTagName(element, name); 98 XmlUtils.removeNode(child); 99 child = (Element ) value; 100 Node node = element.getOwnerDocument().importNode(child, true); 101 element.appendChild(node); 102 } 103 else { 104 Element child = XmlUtils.getFirstChildByTagName(element, name); 105 if (value != null) { 106 if (child == null) { 107 child = element.getOwnerDocument().createElement(name); 108 element.appendChild(child); 109 } 110 XmlUtils.setTextValue(child, (String ) value); 111 } 112 else { 113 XmlUtils.removeNode(child); 114 } 115 } 116 } 117 118 public boolean isReadableProperty(String propertyName) throws BeansException { 119 return true; 120 } 121 122 public boolean isWritableProperty(String propertyName) throws BeansException { 123 return true; 124 } 125 126 } 127 | Popular Tags |