List of usage examples for org.dom4j Element remove
boolean remove(Text text);
Text
if the node is an immediate child of this element. From source file:com.jeeframework.util.xml.XMLProperties.java
License:Open Source License
/** * Deletes the specified property./*from w ww . j a v a 2s. co m*/ * * @param name the property to delete. */ public synchronized void deleteProperty(String name) { // Remove property from cache. propertyCache.remove(name); String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML hierarchy. Element element = document.getRootElement(); for (int i = 0; i < propName.length - 1; i++) { element = element.element(propName[i]); // Can't find the property so return. if (element == null) { return; } } // Found the correct element to remove, so remove it... element.remove(element.element(propName[propName.length - 1])); if (element.elements().size() == 0) { element.getParent().remove(element); } // .. then write to disk. saveProperties(); }
From source file:com.liferay.alloy.tools.builder.base.BaseBuilder.java
License:Open Source License
protected Document mergeXMLAttributes(Document doc1, Document doc2) { Element doc2Root = doc2.getRootElement(); Element doc1Root = doc1.getRootElement(); Element docRoot = doc2Root.createCopy(); docRoot.clearContent();/*from ww w.ja v a 2 s . com*/ if (doc1Root != null) { Iterator<Object> attributesIterator = doc1Root.attributeIterator(); while (attributesIterator.hasNext()) { org.dom4j.Attribute attribute = (org.dom4j.Attribute) attributesIterator.next(); if (attribute.getName().equals("extends")) { continue; } docRoot.addAttribute(attribute.getName(), attribute.getValue()); } Element descriptionElement = doc1Root.element("description"); if (descriptionElement != null) { docRoot.add(descriptionElement.createCopy()); } } DocumentFactory factory = SAXReaderUtil.getDocumentFactory(); Document doc = factory.createDocument(); doc.setRootElement(docRoot); List<Element> doc2Components = doc2Root.elements(_COMPONENT); for (Element doc2Component : doc2Components) { Element component = doc2Component.createCopy(); String name = doc2Component.attributeValue("name"); Element doc1Component = getComponentNode(doc1, name); if (doc1Component != null) { Element doc1ComponentDescriptionElement = doc1Component.element("description"); if (doc1ComponentDescriptionElement != null) { Element descriptionElement = component.element("description"); if (descriptionElement != null) { component.remove(descriptionElement); } component.add(doc1ComponentDescriptionElement.createCopy()); } Iterator<Object> attributesIterator = doc1Component.attributeIterator(); while (attributesIterator.hasNext()) { org.dom4j.Attribute attribute = (org.dom4j.Attribute) attributesIterator.next(); component.addAttribute(attribute.getName(), attribute.getValue()); } Element doc1AttributesNode = doc1Component.element(_ATTRIBUTES); Element attributesNode = component.element(_ATTRIBUTES); if ((doc1AttributesNode != null) && (attributesNode != null)) { List<Element> doc1Attributes = doc1AttributesNode.elements(_ATTRIBUTE); List<Element> attributes = attributesNode.elements(_ATTRIBUTE); for (Element doc1Attribute : doc1Attributes) { Element attribute = getElementByName(attributes, doc1Attribute.elementText("name")); if (attribute != null) { attributesNode.remove(attribute); } attributesNode.add(doc1Attribute.createCopy()); } } Element doc1EventsNode = doc1Component.element(_EVENTS); Element eventsNode = component.element(_EVENTS); if ((doc1EventsNode != null) && (eventsNode != null)) { List<Element> doc1Events = doc1EventsNode.elements(_EVENT); List<Element> events = eventsNode.elements(_EVENT); for (Element doc1Event : doc1Events) { Element event = getElementByName(events, doc1Event.elementText("name")); if (event != null) { eventsNode.add(event); } eventsNode.add(doc1Event.createCopy()); } } } doc.getRootElement().add(component); } if (doc1Root != null) { List<Element> doc1Components = doc1Root.elements(_COMPONENT); for (Element doc1Component : doc1Components) { Element component = doc1Component.createCopy(); String name = doc1Component.attributeValue("name"); Element doc2Component = getComponentNode(doc2, name); if (doc2Component == null) { doc.getRootElement().add(component); } } } return doc; }
From source file:com.liferay.portal.ejb.PortletManagerImpl.java
License:Open Source License
private Set _readPortletXML(String servletContextName, String xml, Map portletsPool) throws DocumentException, IOException { Set portletIds = new HashSet(); if (xml == null) { return portletIds; }//from ww w. j a va2 s . c o m /*EntityResolver resolver = new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { InputStream is = getClass().getClassLoader().getResourceAsStream( "com/liferay/portal/resources/portlet-app_1_0.xsd"); return new InputSource(is); } };*/ SAXReader reader = new SAXReader(); //reader.setEntityResolver(resolver); Document doc = reader.read(new StringReader(xml)); Element root = doc.getRootElement(); Set userAttributes = new HashSet(); Iterator itr1 = root.elements("user-attribute").iterator(); while (itr1.hasNext()) { Element userAttribute = (Element) itr1.next(); String name = userAttribute.elementText("name"); userAttributes.add(name); } itr1 = root.elements("portlet").iterator(); while (itr1.hasNext()) { Element portlet = (Element) itr1.next(); String portletId = portlet.elementText("portlet-name"); if (servletContextName != null) { portletId = servletContextName + PortletConfigImpl.WAR_SEPARATOR + portletId; } portletIds.add(portletId); Portlet portletModel = (Portlet) portletsPool.get(portletId); if (portletModel == null) { portletModel = new Portlet(new PortletPK(portletId, _SHARED_KEY, _SHARED_KEY)); portletsPool.put(portletId, portletModel); } if (servletContextName != null) { portletModel.setWARFile(true); } portletModel.setPortletClass(portlet.elementText("portlet-class")); Iterator itr2 = portlet.elements("init-param").iterator(); while (itr2.hasNext()) { Element initParam = (Element) itr2.next(); portletModel.getInitParams().put(initParam.elementText("name"), initParam.elementText("value")); } Element expirationCache = portlet.element("expiration-cache"); if (expirationCache != null) { portletModel.setExpCache(new Integer(GetterUtil.getInteger(expirationCache.getText()))); } itr2 = portlet.elements("supports").iterator(); while (itr2.hasNext()) { Element supports = (Element) itr2.next(); String mimeType = supports.elementText("mime-type"); Iterator itr3 = supports.elements("portlet-mode").iterator(); while (itr3.hasNext()) { Element portletMode = (Element) itr3.next(); Set mimeTypeModes = (Set) portletModel.getPortletModes().get(mimeType); if (mimeTypeModes == null) { mimeTypeModes = new HashSet(); portletModel.getPortletModes().put(mimeType, mimeTypeModes); } mimeTypeModes.add(portletMode.getTextTrim().toLowerCase()); } } Set supportedLocales = portletModel.getSupportedLocales(); supportedLocales.add(Locale.getDefault().getLanguage()); itr2 = portlet.elements("supported-locale").iterator(); while (itr2.hasNext()) { Element supportedLocaleEl = (Element) itr2.next(); String supportedLocale = supportedLocaleEl.getText(); supportedLocales.add(supportedLocale); } portletModel.setResourceBundle(portlet.elementText("resource-bundle")); Element portletInfo = portlet.element("portlet-info"); String portletInfoTitle = null; String portletInfoShortTitle = null; String portletInfoKeyWords = null; if (portletInfo != null) { portletInfoTitle = portletInfo.elementText("title"); portletInfoShortTitle = portletInfo.elementText("short-title"); portletInfoKeyWords = portletInfo.elementText("keywords"); } portletModel .setPortletInfo(new PortletInfo(portletInfoTitle, portletInfoShortTitle, portletInfoKeyWords)); Element portletPreferences = portlet.element("portlet-preferences"); String defaultPreferences = null; String prefsValidator = null; if (portletPreferences != null) { Element prefsValidatorEl = portletPreferences.element("preferences-validator"); String prefsValidatorName = null; if (prefsValidatorEl != null) { prefsValidator = prefsValidatorEl.getText(); portletPreferences.remove(prefsValidatorEl); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(baos, OutputFormat.createCompactFormat()); writer.write(portletPreferences); defaultPreferences = baos.toString(); } portletModel.setDefaultPreferences(defaultPreferences); portletModel.setPreferencesValidator(prefsValidator); if (!portletModel.isWARFile() && Validator.isNotNull(prefsValidator) && GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) { try { PreferencesValidator prefsValidatorObj = PortalUtil.getPreferencesValidator(portletModel); prefsValidatorObj.validate(PortletPreferencesSerializer.fromDefaultXML(defaultPreferences)); } catch (Exception e) { _log.warn("Portlet with the name " + portletId + " does not have valid default preferences"); } } List roles = new ArrayList(); itr2 = portlet.elements("security-role-ref").iterator(); while (itr2.hasNext()) { Element role = (Element) itr2.next(); roles.add(role.elementText("role-name")); } portletModel.setRolesArray((String[]) roles.toArray(new String[0])); portletModel.getUserAttributes().addAll(userAttributes); } return portletIds; }
From source file:com.poka.util.XmlSax.java
public boolean deleteMachineInfo(MachinesCfg cfg) { Document doc = load(bankFile, false); Element rootElm = doc.getRootElement(); Element root1Elm = rootElm.element("machines"); if (root1Elm == null) { root1Elm = rootElm.addElement("machines"); }/*from www . j a v a 2s. c om*/ List nodes = root1Elm.elements("machine"); boolean flag = false; for (Iterator it = nodes.iterator(); it.hasNext();) { Element elm = (Element) it.next(); if (elm.attributeValue("ip").trim().equals(cfg.getIp().trim()) && elm.attributeValue("type").trim().equals("" + cfg.getType())) { root1Elm.remove(elm); break; } } return writeToXml(doc, bankFile); }
From source file:com.smartwork.im.utils.XMLProperties.java
License:Open Source License
/** * Sets a property to an array of values. Multiple values matching the same property * is mapped to an XML file as multiple elements containing each value. * For example, using the name "foo.bar.prop", and the value string array containing * {"some value", "other value", "last value"} would produce the following XML: * <pre>/*from w ww . j a v a 2s. com*/ * <foo> * <bar> * <prop>some value</prop> * <prop>other value</prop> * <prop>last value</prop> * </bar> * </foo> * </pre> * * @param name the name of the property. * @param values the values for the property (can be empty but not null). */ public void setProperties(String name, List<String> values) { String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML heirarchy, // stopping one short. Element element = document.getRootElement(); for (int i = 0; i < propName.length - 1; i++) { // If we don't find this part of the property in the XML heirarchy // we add it as a new node if (element.element(propName[i]) == null) { element.addElement(propName[i]); } element = element.element(propName[i]); } String childName = propName[propName.length - 1]; // We found matching property, clear all children. List toRemove = new ArrayList(); Iterator iter = element.elementIterator(childName); while (iter.hasNext()) { toRemove.add(iter.next()); } for (iter = toRemove.iterator(); iter.hasNext();) { element.remove((Element) iter.next()); } // Add the new children. for (String value : values) { element.addElement(childName).setText(value); } saveProperties(); // Generate event. Map<String, Object> params = new HashMap<String, Object>(); params.put("value", values); PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params); }
From source file:com.smartwork.im.utils.XMLProperties.java
License:Open Source License
/** * Deletes the specified property.//from w w w . ja v a2 s. c om * * @param name the property to delete. */ public synchronized void deleteProperty(String name) { // Remove property from cache. propertyCache.remove(name); String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML heirarchy. Element element = document.getRootElement(); for (int i = 0; i < propName.length - 1; i++) { element = element.element(propName[i]); // Can't find the property so return. if (element == null) { return; } } // Found the correct element to remove, so remove it... element.remove(element.element(propName[propName.length - 1])); // .. then write to disk. saveProperties(); // Generate event. PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_deleted, Collections.emptyMap()); }
From source file:com.stratumsoft.xmlgen.SchemaTypeXmlGenerator.java
License:Open Source License
private void addRestrictedAttributesToElement(Element elementToAddOn, XmlSchemaAttribute attribute) { logger.debug("Adding restricted attribute: {}", attribute.getName()); QName attrQName = attribute.getQName(); if (attrQName != null) { org.dom4j.QName dom4jQName = createDom4jQName(attrQName, attribute.getForm()); Attribute attr = elementToAddOn.attribute(dom4jQName); if (attr != null) { //already exists, so remove it, so we can add the restricted version of it logger.debug("Removing existing attribute\\: {} to add the restricted attribute", dom4jQName.getName()); elementToAddOn.remove(attr); }/*from w w w . j a v a2s . c o m*/ attr = factory.createAttribute(elementToAddOn, dom4jQName, ""); elementToAddOn.add(attr); } }
From source file:com.stratumsoft.xmlgen.SchemaTypeXmlGenerator.java
License:Open Source License
/** * Handle the complex type simple content restriction * * @param restriction/*from ww w .j a v a2 s.c o m*/ * @param dom4jEl */ private void handleSimpleContentRestriction(XmlSchemaSimpleContentRestriction restriction, Element dom4jEl) { logger.debug("Handling simple content restriction"); // restriction.getBaseType(); //todo: process the base schema simpletype if present QName baseTypeName = restriction.getBaseTypeName(); logger.debug("Simple content restriction base type name = {}", baseTypeName); XmlSchemaType type = schemaColl.getTypeByQName(baseTypeName); if (type != null) { if (type instanceof XmlSchemaSimpleType) { logger.trace("Simple content restriction base type is simple type"); handleSimpleType((XmlSchemaSimpleType) type, dom4jEl); } else if (type instanceof XmlSchemaComplexType) { logger.trace("Simple content restriction base type is complex type"); handleComplexType((XmlSchemaComplexType) type, dom4jEl); //for restriction if there are any attributes specified, they are restrictions of the //base complex type attributes - so removing any attributes added in the prev step //and specified again and re-process it List<XmlSchemaAttributeOrGroupRef> attributeOrGroupRefs = restriction.getAttributes(); if (attributeOrGroupRefs != null) { logger.debug("simple content restriction is overriding base type attributes"); //collect all attributes that are being overridden List<XmlSchemaAttribute> attributes = new ArrayList<>(); for (XmlSchemaAttributeOrGroupRef o : attributeOrGroupRefs) { if (o instanceof XmlSchemaAttribute) { attributes.add((XmlSchemaAttribute) o); } else if (o instanceof XmlSchemaAttributeGroupRef) { XmlSchemaRef<XmlSchemaAttributeGroup> ref = ((XmlSchemaAttributeGroupRef) o).getRef(); if (ref != null) { XmlSchemaAttributeGroup attrGroup = ref.getTarget(); if (attrGroup != null) { List<XmlSchemaAttributeGroupMember> attrGroupMembers = attrGroup .getAttributes(); for (XmlSchemaAttributeGroupMember attrGroupMember : attrGroupMembers) { if (attrGroupMember instanceof XmlSchemaAttribute) { attributes.add((XmlSchemaAttribute) attrGroupMember); } //else todo: check if we need to handle group refs within group? } } } } // end else if } //end while //now if any attribute with the same name as the overridden attribute was added from the base type //remove it and add it again for (XmlSchemaAttribute schAttr : attributes) { QName qname = schAttr.getQName(); org.dom4j.QName dom4jQName = createDom4jQName(qname, schAttr.getForm()); logger.debug("Created dom4j qname: {} from XmlSchema qname: {}", dom4jQName, qname); //remove this attribute Attribute dom4jAttr = dom4jEl.attribute(dom4jQName); dom4jEl.remove(dom4jAttr); //handle this attribute again - but this time with the restrictions defined for it handleAttribute(schAttr, dom4jEl); } } //end if } //end else if } //end if }
From source file:com.suneee.core.util.XMLProperties.java
License:Open Source License
/** * Sets a property to an array of values. Multiple values matching the same property * is mapped to an XML file as multiple elements containing each value. * For example, using the name "foo.bar.prop", and the value string array containing * {"some value", "other value", "last value"} would produce the following XML: * <pre>//from w ww . ja v a 2 s. com * <foo> * <bar> * <prop>some value</prop> * <prop>other value</prop> * <prop>last value</prop> * </bar> * </foo> * </pre> * * @param name the name of the property. * @param values the values for the property (can be empty but not null). */ public void setProperties(String name, List<String> values) { String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML heirarchy, // stopping one short. Element element = document.getRootElement(); for (int i = 0; i < propName.length - 1; i++) { // If we don't find this part of the property in the XML heirarchy // we add it as a new node if (element.element(propName[i]) == null) { element.addElement(propName[i]); } element = element.element(propName[i]); } String childName = propName[propName.length - 1]; // We found matching property, clear all children. List<Element> toRemove = new ArrayList<Element>(); Iterator iter = element.elementIterator(childName); while (iter.hasNext()) { toRemove.add((Element) iter.next()); } for (iter = toRemove.iterator(); iter.hasNext();) { element.remove((Element) iter.next()); } // Add the new children. for (String value : values) { Element childElement = element.addElement(childName); if (value.startsWith("<![CDATA[")) { Iterator it = childElement.nodeIterator(); while (it.hasNext()) { Node node = (Node) it.next(); if (node instanceof CDATA) { childElement.remove(node); break; } } childElement.addCDATA(value.substring(9, value.length() - 3)); } else { childElement.setText(StringEscapeUtils.escapeXml(value)); } } saveProperties(); // Generate event. /*Map<String, Object> params = new HashMap<String, Object>(); params.put("value", values); PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params);*/ }
From source file:com.suneee.core.util.XMLProperties.java
License:Open Source License
/** * Sets the value of the specified property. If the property doesn't * currently exist, it will be automatically created. * * @param name the name of the property to set. * @param value the new value for the property. *//*from ww w .ja v a2 s.c o m*/ public synchronized void setProperty(String name, String value) { if (!StringEscapeUtils.escapeXml(name).equals(name)) { throw new IllegalArgumentException("Property name cannot contain XML entities."); } if (name == null) { return; } if (value == null) { value = ""; } // Set cache correctly with prop name and value. propertyCache.put(name, value); String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML heirarchy. Element element = document.getRootElement(); for (String aPropName : propName) { // If we don't find this part of the property in the XML heirarchy // we add it as a new node if (element.element(aPropName) == null) { element.addElement(aPropName); } element = element.element(aPropName); } // Set the value of the property in this node. if (value.startsWith("<![CDATA[")) { Iterator it = element.nodeIterator(); while (it.hasNext()) { Node node = (Node) it.next(); if (node instanceof CDATA) { element.remove(node); break; } } element.addCDATA(value.substring(9, value.length() - 3)); } else { element.setText(value); } // Write the XML properties to disk saveProperties(); // Generate event. /* Map<String, Object> params = new HashMap<String, Object>(); params.put("value", value); PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params);*/ }