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:de.tu_berlin.cit.intercloud.xmpp.core.packet.Roster.java
License:Open Source License
/** * Adds a new item to the roster. If the roster packet already contains an item * using the same JID, the information in the existing item will be overwritten * with the new information.<p>//from w ww . ja v a 2s.co m * * The XMPP specification recommends that if the roster item is associated with another * instant messaging user (human), that the JID be in bare form (e.g. user@domain). * Use the {@link JID#toBareJID() toBareJID()} method for a bare JID. * * @param jid the JID. * @param name the nickname. * @param ask the ask type. * @param subscription the subscription type. * @param groups a Collection of groups. * @return the newly created item. */ @SuppressWarnings("unchecked") public Item addItem(JID jid, String name, Ask ask, Subscription subscription, Collection<String> groups) { if (jid == null) { throw new NullPointerException("JID cannot be null"); } if (subscription == null) { throw new NullPointerException("Subscription cannot be null"); } Element query = element.element(new QName("query", Namespace.get("jabber:iq:roster"))); if (query == null) { query = element.addElement("query", "jabber:iq:roster"); } Element item = null; for (Iterator<Element> i = query.elementIterator("item"); i.hasNext();) { Element el = i.next(); if (el.attributeValue("jid").equals(jid.toString())) { item = el; } } if (item == null) { item = query.addElement("item"); } item.addAttribute("jid", jid.toBareJID()); item.addAttribute("name", name); if (ask != null) { item.addAttribute("ask", ask.toString()); } item.addAttribute("subscription", subscription.toString()); // Erase existing groups in case the item previously existed. for (Iterator<Element> i = item.elementIterator("group"); i.hasNext();) { item.remove(i.next()); } // Add in groups. if (groups != null) { for (String group : groups) { item.addElement("group").setText(group); } } return new Item(jid, name, ask, subscription, groups); }
From source file:de.tu_berlin.cit.intercloud.xmpp.core.packet.Roster.java
License:Open Source License
/** * Removes an item from this roster.//from w w w .j a va 2 s .c o m * * @param jid the JID of the item to remove. */ @SuppressWarnings("unchecked") public void removeItem(JID jid) { Element query = element.element(new QName("query", Namespace.get("jabber:iq:roster"))); if (query != null) { for (Iterator<Element> i = query.elementIterator("item"); i.hasNext();) { Element item = i.next(); if (item.attributeValue("jid").equals(jid.toString())) { query.remove(item); return; } } } }
From source file:de.tu_berlin.cit.rwx4j.xmpp.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 ww w .j av a 2 s . c o m * <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 childElement = element.addElement(childName); if (value.startsWith("<![CDATA[")) { childElement.addCDATA(value.substring(9, value.length() - 3)); } else { childElement.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:dk.netarkivet.deploy.XmlStructure.java
License:Open Source License
/** * The current tree will be overwritten by the overwriter tree. The new branches in overwriter will be added to the * current tree. For the leafs which are present in both overwriter and current, the value in the current-leaf will * be overwritten by the overwriter-leaf. * <p>/* ww w . j a va 2 s .c om*/ * The subtrees which exists in both the overwriter and the current tree, this function will be run recursively on * these subtrees. * * @param current The base element * @param overwriter The element to have its values overwrite the base element * @throws IllegalState If a leaf in current is about to be replaced by a tree */ @SuppressWarnings("unchecked") private void overWriting(Element current, Element overwriter) throws IllegalState { ArgumentNotValid.checkNotNull(current, "Element current"); ArgumentNotValid.checkNotNull(overwriter, "Element overwriter"); // get the attributes to be overwritten List<Element> attributes = overwriter.elements(); List<Element> addElements = new ArrayList<Element>(); // add branch if it does not exists for (Element e : attributes) { // find corresponding attribute in current element List<Element> curElems = current.elements(e.getName()); // if no such elements in current tree, add branch. if (curElems.isEmpty()) { addElements.add(e); } else { // List<Element> overElems = overwriter.elements(e.getName()); // if the lists have a 1-1 ratio, then overwrite if (curElems.size() == 1 && overElems.size() == 1) { // only one branch, thus overwrite Element curE = curElems.get(0); // if leaf overwrite value, otherwise repeat for branches. if (curE.isTextOnly()) { curE.setText(e.getText().trim()); // TODO Is this necessary } else { overWriting(curE, e); } } else { // a different amount of current branches exist (not 0). // Therefore remove the branches in current tree, // and add replacements. for (Element curE : curElems) { current.remove(curE); } // add only current branch, since the others will follow. addElements.add(e); } } } // add all the new branches to the current branch. for (Element e : addElements) { current.add(e.createCopy()); } }
From source file:edu.scripps.fl.pubchem.xml.PubChemXMLDoc.java
License:Apache License
public void fixAttribute(Document doc) { Element documentRoot = (Element) doc.selectSingleNode("PC-AssayContainer"); List<Attribute> attributes = documentRoot.attributes(); documentRoot.remove(attributes.get(0)); documentRoot.addAttribute("xs:schemaLocation", "http://www.ncbi.nlm.nih.gov ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem.xsd"); }
From source file:edu.ucsd.library.dams.jhove.MyJhoveBase.java
License:Open Source License
public static void removeNS(Element elem) { elem.remove(elem.getNamespace()); elem.setQName(new QName(elem.getQName().getName(), Namespace.NO_NAMESPACE)); // fix children List children = elem.elements(); for (int i = 0; i < children.size(); i++) { Element child = (Element) children.get(i); removeNS(child);// w w w . java2 s .com } }
From source file:eu.sisob.uma.crawler.ResearchersCrawlers.deprecated.LocalResearchersWebPagesExtractor.java
License:Open Source License
public static void P1_step_collectResearcherLinks(String xmlFilePath, int numberOfCrawlers, String sControlInstitutionName) { try {//from w w w.j av a2 s . c om /* * rootfolder is a folder where intermediate crawl data is * stored. */ String rootFolder = "temp/"; FileFootils.deleteDir(rootFolder); /* * numberOfCrawlers shows the number of concurrent threads * that should be initiated for crawling. */ File xmlFile = new File(xmlFilePath); org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader(); org.dom4j.Document document = reader.read(xmlFile); org.dom4j.Element root = document.getRootElement(); String sInstitutionName = ""; String sWebAddress = ""; String sUnitOfAssessment_Description = ""; String sResearchGroupDescription = ""; String sResearchers = ""; String sResearchersInitials = ""; PageFetcher.startConnectionMonitorThread(); WebCrawler.setTraceLinkName(true); WebCrawler.setTracePageName(true); TreeMap<String, TreeMap<String, List<CandidateTypeURL>>> finalResults = new TreeMap<String, TreeMap<String, List<CandidateTypeURL>>>(); boolean bFlagInstitutionName = false; String sControlUnitOfAssessment_Description = ""; boolean bFlagUnitOfAssessmentName = false; boolean bSaveFile = true; boolean bSetEmptyAllResearchers = true; if (bSetEmptyAllResearchers) { File fField = new File(xmlFilePath.replace(".xml", "backup.xml")); FileOutputStream fileOS = new java.io.FileOutputStream(fField, false); OutputStreamWriter writer = new java.io.OutputStreamWriter(fileOS, "UTF-8"); BufferedWriter bw = new java.io.BufferedWriter(writer); String sOut = document.asXML(); bw.write(sOut); bw.close(); ProjectLogger.LOGGER.info(xmlFilePath + " backuped."); } int[] counterSuccess = new int[3]; int[] counterTotal = new int[3]; for (int i = 0; i < counterSuccess.length; i++) counterSuccess[i] = 0; for (int i = 0; i < counterTotal.length; i++) counterTotal[i] = 0; for (Iterator i1 = root.elementIterator(XMLTags.INSTITUTION); i1.hasNext();) { bSaveFile = false; org.dom4j.Element e1 = (org.dom4j.Element) i1.next(); sInstitutionName = e1.element(XMLTags.INSTITUTION_NAME).getText(); sWebAddress = e1.element(XMLTags.INSTITUTION_WEBADDRESS).getText(); if (sWebAddress.charAt(sWebAddress.length() - 1) != '/') sWebAddress += "/"; if (!sInstitutionName.toLowerCase().contains(sControlInstitutionName.toLowerCase()) && !bFlagInstitutionName) continue; bFlagInstitutionName = true; List<String> subjects = new ArrayList<String>(); ProjectLogger.LOGGER.info("Department phase - " + sInstitutionName); boolean bNeedToSearchDeparmentWebAddress = false; for (Iterator i2 = e1.elementIterator(XMLTags.UNIT_OF_ASSESSMENT); i2.hasNext();) { org.dom4j.Element e2 = (org.dom4j.Element) i2.next(); sUnitOfAssessment_Description = e2.element(XMLTags.UNIT_OF_ASSESSMENT_DESCRIPTION).getText(); //FIXME if(sUnitOfAssessment_Description.length() > 20) sUnitOfAssessment_Description = sUnitOfAssessment_Description.substring(0, 20); if (e2.element(XMLTags.DEPARTMENT_WEB_ADDRESS) != null && e2.element("DepartamentWebAddress").elements().size() != 0) { ProjectLogger.LOGGER .info("\tExist departments webaddress for " + sUnitOfAssessment_Description); } else { subjects.add(sUnitOfAssessment_Description); ProjectLogger.LOGGER .info("\tNot exist departments webaddress for " + sUnitOfAssessment_Description); bNeedToSearchDeparmentWebAddress = true; } } String sSeed = sWebAddress; String sContainPattern = sSeed.replace("http://www.", ""); int iAux = sContainPattern.indexOf("/"); sContainPattern = sContainPattern.substring(0, iAux); if (bNeedToSearchDeparmentWebAddress) { CrawlerDepartamentsV2Controller_deprecated controllerDepts = new CrawlerDepartamentsV2Controller_deprecated( rootFolder + sInstitutionName.replace(" ", ".") + ".Researchers", subjects); controllerDepts.addSeed(sSeed); controllerDepts.setPolitenessDelay(200); controllerDepts.setMaximumCrawlDepth(3); controllerDepts.setMaximumPagesToFetch(-1); controllerDepts.setContainPattern(sContainPattern); controllerDepts.clearPossibleResults(); ProjectLogger.LOGGER .info("======================================================================"); ProjectLogger.LOGGER.info("Begin crawling: " + sInstitutionName + " (" + sWebAddress + ")"); long lTimerAux = java.lang.System.currentTimeMillis(); controllerDepts.start(CrawlerDepartamentsV2_deprecated.class, 1); lTimerAux = java.lang.System.currentTimeMillis() - lTimerAux; ProjectLogger.LOGGER.info("Extracting Links in: " + lTimerAux + " ms"); ProjectLogger.LOGGER .info("======================================================================"); CandidateTypeURL.printResults( "Results of: " + sInstitutionName + " (" + sWebAddress + ") by TYPE", controllerDepts.getPossibleResultsTYPE()); for (Iterator i2 = e1.elementIterator(XMLTags.UNIT_OF_ASSESSMENT); i2.hasNext();) { org.dom4j.Element e2 = (org.dom4j.Element) i2.next(); sUnitOfAssessment_Description = e2.element(XMLTags.UNIT_OF_ASSESSMENT_DESCRIPTION) .getText(); TreeMap<String, List<CandidateTypeURL>> t = controllerDepts.getPossibleResultsTYPE(); Iterator<String> it = t.keySet().iterator(); while (it.hasNext()) { String s = it.next(); if (s.toLowerCase() .equals("department of " + sUnitOfAssessment_Description.toLowerCase())) { if (e2.element(XMLTags.DEPARTMENT_WEB_ADDRESS) != null && e2.element(XMLTags.DEPARTMENT_WEB_ADDRESS).elements().size() != 0) { throw new Exception(sUnitOfAssessment_Description + " must be empty."); } List<CandidateTypeURL> lst = t.get(s); for (CandidateTypeURL ss : lst) { e2.addElement(XMLTags.DEPARTMENT_WEB_ADDRESS).addText(ss.sURL); bSaveFile = true; } break; } } } } ProjectLogger.LOGGER.info("Researcher phase - " + sInstitutionName); if (sContainPattern != "") sContainPattern = sContainPattern; for (Iterator i2 = e1.elementIterator(XMLTags.UNIT_OF_ASSESSMENT); i2.hasNext();) { org.dom4j.Element e2 = (org.dom4j.Element) i2.next(); sUnitOfAssessment_Description = e2.element(XMLTags.UNIT_OF_ASSESSMENT_DESCRIPTION).getText(); //FIXME if(sUnitOfAssessment_Description.length() > 20) sUnitOfAssessment_Description = sUnitOfAssessment_Description.substring(0, 20); List<String> lstDepartmentWebAddress = new ArrayList<String>(); for (Iterator i3 = e2.elementIterator(XMLTags.DEPARTMENT_WEB_ADDRESS); i3.hasNext();) { org.dom4j.Element e3 = (org.dom4j.Element) i3.next(); if (!e3.getText().equals("")) lstDepartmentWebAddress.add(e3.getText()); } if (lstDepartmentWebAddress.size() > 0) { ProjectLogger.LOGGER .info("\tExist departments webaddress for " + sUnitOfAssessment_Description); boolean bExistResearcherWebAddress = false; List<ResearcherNameInfo> researchers = new ArrayList<ResearcherNameInfo>(); for (Iterator i3 = e2.elementIterator(XMLTags.RESEARCHGROUP); i3.hasNext();) { org.dom4j.Element e3 = (org.dom4j.Element) i3.next(); sResearchGroupDescription = e3.element(XMLTags.RESEARCHGROUP_DESCRIPTION).getText(); for (Iterator i4 = e3.elementIterator(XMLTags.RESEARCHER); i4.hasNext();) { org.dom4j.Element e4 = (org.dom4j.Element) i4.next(); if (bSetEmptyAllResearchers) { boolean aux = true; while (aux) { org.dom4j.Element eaux = e4.element(XMLTags.RESEARCHER_WEB_ADDRESS); if (eaux != null) e4.remove(eaux); else aux = false; } } if (e4.element(XMLTags.RESEARCHER_WEB_ADDRESS) == null) { String initials = e4.element(XMLTags.RESEARCHER_INITIALS).getText(); String last_name = e4.element(XMLTags.RESEARCHER_LASTNAME).getText(); String first_name = e4.element(XMLTags.RESEARCHER_FIRSTNAME) == null ? "" : e4.element(XMLTags.RESEARCHER_FIRSTNAME).getText(); String whole_name = e4.element(XMLTags.RESEARCHER_NAME) == null ? "" : e4.element(XMLTags.RESEARCHER_NAME).getText(); ResearcherNameInfo rsi = new ResearcherNameInfo(last_name, initials, first_name, whole_name); researchers.add(rsi); bExistResearcherWebAddress = false; } else if (bSetEmptyAllResearchers) { throw new Exception( "XML element of " + e4.element(XMLTags.RESEARCHER_INITIALS).getText() + "," + e4.element(XMLTags.RESEARCHER_LASTNAME).getText() + " must not have researcher web address at this moment"); } } } if (!bExistResearcherWebAddress) { ProjectLogger.LOGGER.info("\tMiss researchers webaddress for " + sUnitOfAssessment_Description + ". Try to search."); CrawlerResearchesPagesV2Controller_deprecated controllerReseachers = new CrawlerResearchesPagesV2Controller_deprecated( rootFolder + sInstitutionName.replace(" ", ".") + "_" + sUnitOfAssessment_Description.replace(" ", "."), researchers); String sSeeds = ""; for (String s : lstDepartmentWebAddress) { controllerReseachers.addSeed(s); sSeeds += s + ","; } controllerReseachers.setPolitenessDelay(200); controllerReseachers.setMaximumCrawlDepth(3); controllerReseachers.setMaximumPagesToFetch(-1); controllerReseachers.setContainPattern(sContainPattern); controllerReseachers.clearInterestingUrlsDetected(); if (!sUnitOfAssessment_Description.contains(sControlUnitOfAssessment_Description) && !bFlagUnitOfAssessmentName) continue; bFlagUnitOfAssessmentName = true; ProjectLogger.LOGGER .info("======================================================================"); ProjectLogger.LOGGER.info("Begin crawling: " + sUnitOfAssessment_Description + " - " + sInstitutionName + " (" + sSeeds + ")"); long lTimerAux = java.lang.System.currentTimeMillis(); controllerReseachers.start(CrawlerResearchesPagesV2_deprecated.class, 1); controllerReseachers.postProcessResults(); lTimerAux = java.lang.System.currentTimeMillis() - lTimerAux; ProjectLogger.LOGGER.info("Extracting Links in: " + lTimerAux + " ms"); ProjectLogger.LOGGER .info("======================================================================"); CandidateTypeURL.printResults( "Results of: " + sUnitOfAssessment_Description + " - " + sInstitutionName + " (" + sWebAddress + ") by TYPE", controllerReseachers.getInterestingUrlsDetected()); counterTotal[0] = 0; counterSuccess[0] = 0; for (Iterator i3 = e2.elementIterator(XMLTags.RESEARCHGROUP); i3.hasNext();) { org.dom4j.Element e3 = (org.dom4j.Element) i3.next(); for (Iterator i4 = e3.elementIterator(XMLTags.RESEARCHER); i4.hasNext();) { counterTotal[0]++; org.dom4j.Element e4 = (org.dom4j.Element) i4.next(); String initials = e4.element(XMLTags.RESEARCHER_INITIALS) == null ? "" : e4.element(XMLTags.RESEARCHER_INITIALS).getText(); String last_name = e4.element(XMLTags.RESEARCHER_LASTNAME) == null ? "" : e4.element(XMLTags.RESEARCHER_LASTNAME).getText(); String first_name = e4.element(XMLTags.RESEARCHER_FIRSTNAME) == null ? "" : e4.element(XMLTags.RESEARCHER_FIRSTNAME).getText(); String whole_name = e4.element(XMLTags.RESEARCHER_NAME) == null ? "" : e4.element(XMLTags.RESEARCHER_NAME).getText(); ResearcherNameInfo rsi = new ResearcherNameInfo(last_name, initials, first_name, whole_name); TreeMap<String, List<CandidateTypeURL>> t = controllerReseachers .getInterestingUrlsDetected(); List<CandidateTypeURL> lst = t.get( CrawlerResearchesPagesV2Controller_deprecated.RESEARCHER_RESULT_TAG); boolean bExist = false; if (lst != null) { boolean lock1 = true; for (CandidateTypeURL ss : lst) { if (rsi.equals(ss.data)) { e4.addElement(XMLTags.RESEARCHER_WEB_ADDRESS) .addAttribute(XMLTags.RESEARCHER_WEB_ADDRESS_ATTR_TYPE, ss.sSubType) .addAttribute(XMLTags.RESEARCHER_WEB_ADDRESS_ATTR_EXT, ss.sExt) .addText(ss.sURL); lock1 = false; bSaveFile = true; bExist = true; } } } if (bExist) { counterSuccess[0]++; } } } ProjectLogger.LOGGER.info("Researches results: " + sInstitutionName + " - " + sUnitOfAssessment_Description + " - " + counterSuccess[0] + " / " + counterTotal[0]); } else { ProjectLogger.LOGGER.info( "\tExist researchers webaddress for " + sUnitOfAssessment_Description + "."); counterTotal[0] = 0; counterSuccess[0] = 0; for (Iterator i3 = e2.elementIterator(XMLTags.RESEARCHGROUP); i3.hasNext();) { org.dom4j.Element e3 = (org.dom4j.Element) i3.next(); for (Iterator i4 = e3.elementIterator(XMLTags.RESEARCHER); i4.hasNext();) { counterTotal[0]++; org.dom4j.Element e4 = (org.dom4j.Element) i4.next(); if (e4.element(XMLTags.RESEARCHER_WEB_ADDRESS) != null && e4.element(XMLTags.RESEARCHER_WEB_ADDRESS).elements().size() > 0) { counterSuccess[0]++; } } } ProjectLogger.LOGGER.info( "Results exist: " + sInstitutionName + " - " + sUnitOfAssessment_Description + " - " + counterSuccess[0] + " / " + counterTotal[0]); } } else { ProjectLogger.LOGGER .info("\tNot exist departments webaddress for " + sUnitOfAssessment_Description); counterTotal[0] = 0; counterSuccess[0] = 0; for (Iterator i3 = e2.elementIterator(XMLTags.RESEARCHGROUP); i3.hasNext();) { org.dom4j.Element e3 = (org.dom4j.Element) i3.next(); for (Iterator i4 = e3.elementIterator(XMLTags.RESEARCHER); i4.hasNext();) { counterTotal[0]++; org.dom4j.Element e4 = (org.dom4j.Element) i4.next(); if (e4.element(XMLTags.RESEARCHER_WEB_ADDRESS) != null && e4.element(XMLTags.RESEARCHER_WEB_ADDRESS).elements().size() > 0) { counterSuccess[0]++; } } } if (counterSuccess[0] > 0) ProjectLogger.LOGGER.info( "\tExist researchers webaddress for " + sUnitOfAssessment_Description + "."); else ProjectLogger.LOGGER.info("\tNot exist researchers webaddress for " + sUnitOfAssessment_Description + "."); ProjectLogger.LOGGER .info("Results exist: " + sInstitutionName + " - " + sUnitOfAssessment_Description + " - " + counterSuccess[0] + " / " + counterTotal[0]); } } counterSuccess[1] += counterSuccess[0]; counterTotal[1] += counterTotal[0]; if (bSaveFile) { File fField = new File(xmlFilePath); FileOutputStream fileOS = new java.io.FileOutputStream(fField, false); OutputStreamWriter writer = new java.io.OutputStreamWriter(fileOS, "UTF-8"); BufferedWriter bw = new java.io.BufferedWriter(writer); String sOut = document.asXML(); bw.write(sOut); bw.close(); ProjectLogger.LOGGER.info(xmlFile + " updated."); } } ProjectLogger.LOGGER.info("Researches results:" + counterSuccess[1] + " / " + counterTotal[1]); } catch (Exception ex) { ProjectLogger.LOGGER.error(ex.getMessage(), ex); } finally { PageFetcher.stopConnectionMonitorThread(); } }
From source file:fedora.utilities.install.container.Tomcat5ServerXML.java
License:fedora commons license
/** * Adds the attribute to the element if the attributeValue is not equal to * defaultValue. If attributeValue is null or equals defaultValue, remove * the attribute from the element if it is present. * * @param element/*from ww w .ja v a 2 s .c o m*/ * @param attributeName * @param attributeValue * @param defaultValue */ private void addAttribute(Element element, String attributeName, String attributeValue, String defaultValue) { if (attributeValue == null || attributeValue.equals(defaultValue)) { Attribute attribute = (Attribute) element.selectSingleNode(attributeName); if (attribute != null) { element.remove(attribute); } } else { element.addAttribute(attributeName, attributeValue); } }
From source file:fr.gouv.culture.vitam.utils.XmlDom.java
License:Open Source License
public final static void removeAllNamespaces(Document doc) { Element root = doc.getRootElement(); Namespace namespace = root.getNamespace(); if (namespace != Namespace.NO_NAMESPACE) { root.remove(namespace); removeNamespaces(root.content()); }/*from w w w. j av a 2 s . c o m*/ }
From source file:fr.gouv.vitam.xml.XmlDom4jTools.java
License:Open Source License
public final static void removeEmptyElement(Element root) { // look first at attribute if (root.attributeCount() > 0) { @SuppressWarnings("unchecked") Iterator<Attribute> attribs = root.attributeIterator(); List<Attribute> toremove = new ArrayList<>(); while (attribs.hasNext()) { Attribute attribute = (Attribute) attribs.next(); if (attribute.getValue().length() == 0) { toremove.add(attribute); }/*from w w w .ja v a 2 s . c o m*/ //removeEmptyAttribute(attribute); } for (Attribute attribute : toremove) { root.remove(attribute); } toremove.clear(); } @SuppressWarnings("unchecked") Iterator<Element> elements = root.elementIterator(); List<Element> toremove = new ArrayList<>(); while (elements.hasNext()) { Element elt = (Element) elements.next(); // look at its descendant removeEmptyElement(elt); if (elt.attributeCount() > 0) { continue; } if (elt.hasContent()) { continue; } toremove.add(elt); //elt.detach(); } for (Element element : toremove) { root.remove(element); } toremove.clear(); }