Java Code Examples for org.dom4j.Element.detach()

The following are Jave code examples for showing how to use detach() of the org.dom4j.Element class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ats-framework   File: XmlNode.java   View Source Code Vote up 6 votes
/**
 * If some node is to be skipped, we do it in this method
 * 
 * @param matchedNode
 */
public void removeChild( Element matchedNode ) {

    // remove the matched node
    matchedNode.detach();

    // now we have to regenerate info that might have been affected
    this.value = this.node.getTextTrim();

    this.children.clear();
    List<Element> childrenElements = this.node.elements();
    for (Element child : childrenElements) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            this.children.add(new XmlNode(this, child));
        }
    }
}
 
Example 2
Project: ats-framework   File: XmlText.java   View Source Code Vote up 6 votes
/**
 * Remove a XML element
 *
 * @param xpath XPath , pointing to a XML element
 * @return this instance
 * @throws XMLException
 */
@PublicAtsApi
public XmlText remove(
                       String xpath ) throws XMLException {

    if (StringUtils.isNullOrEmpty(xpath)) {
        throw new XMLException("Null/empty xpath is not allowed.");
    }

    Element element = findElement(xpath);

    if (element != null) {

        if (element.isRootElement()) {
            throw new XMLException("You cannot remove the root element of the XML document.");
        }

        element.detach();
    } else {
        throw new XMLException("'" + xpath + "' is not a valid path");
    }

    return this;
}
 
Example 3
Project: Reer   File: DOM4JSettingsNode.java   View Source Code Vote up 5 votes
public void removeAllChildren() {
    List list = element.elements();
    Iterator iterator = list.iterator();

    while (iterator.hasNext()) {
        Element child = (Element) iterator.next();
        child.detach();
    }
}
 
Example 4
Project: Reer   File: DOM4JSerializer.java   View Source Code Vote up 5 votes
public static void exportToFile(ExportInteraction exportInteraction, ExtensionFileFilter fileFilter, DOM4JSettingsNode settingsNode) {
    File file = promptForFile(exportInteraction, fileFilter);
    if (file == null) {
        //the user canceled.
        return;
    }

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        LOGGER.error("Could not write to file: " + file.getAbsolutePath(), e);
        exportInteraction.reportError("Could not write to file: " + file.getAbsolutePath());
        return;
    }

    try {
        XMLWriter xmlWriter = new XMLWriter(fileOutputStream, OutputFormat.createPrettyPrint());
        Element rootElement = settingsNode.getElement();
        rootElement.detach();

        Document document = DocumentHelper.createDocument(rootElement);

        xmlWriter.write(document);
    } catch (Throwable t) {
        LOGGER.error("Internal error. Failed to save.", t);
        exportInteraction.reportError("Internal error. Failed to save.");
    } finally {
        closeQuietly(fileOutputStream);
    }
}
 
Example 5
Project: joai-project   File: DcsDataRecord.java   View Source Code Vote up 5 votes
/**
 *  Remove specified status entry from the status entry list
 *
 * @param  changeDate     key used to specify existing status entry
 * @exception  Exception  NOT YET DOCUMENTED
 */
public synchronized void deleteStatusEntry(String changeDate) throws Exception {
	Element historyElement = getHistoryElement(changeDate);

	if (historyElement == null) {
		throw new Exception("historyElement not found for " + changeDate);
	}
	historyElement.detach();
	entryList = null;
}
 
Example 6
Project: lams   File: AbstractType.java   View Source Code Vote up 5 votes
protected static void replaceNode(Node container, Element value) {
	if ( container!=value ) { //not really necessary, I guess...
		Element parent = container.getParent();
		container.detach();
		value.setName( container.getName() );
		value.detach();
		parent.add(value);
	}
}
 
Example 7
Project: gitplex-mit   File: DatabaseMigrator.java   View Source Code Vote up 5 votes
private void migrate1(File dataDir, Stack<Integer> versions) {
	for (File file: dataDir.listFiles()) {
		if (file.getName().startsWith("CodeComments.xml")) {
			VersionedDocument dom = VersionedDocument.fromFile(file);
			for (Element element: dom.getRootElement().elements()) {
				Element branchRefElement = element.element("branchRef");
				if (branchRefElement != null)
					branchRefElement.detach();
			}
			dom.writeToFile(file, false);
		}
	}	
}
 
Example 8
Project: gitplex-mit   File: DatabaseMigrator.java   View Source Code Vote up 5 votes
private void migrate2(File dataDir, Stack<Integer> versions) {
	for (File file: dataDir.listFiles()) {
		if (file.getName().startsWith("Depots.xml")) {
			VersionedDocument dom = VersionedDocument.fromFile(file);
			for (Element element: dom.getRootElement().elements()) {
				Element gateKeeperElement = element.element("gateKeeper");
				gateKeeperElement.detach();
				element.addElement("gateKeepers");
			}
			dom.writeToFile(file, false);
		}
	}	
}
 
Example 9
Project: gitplex-mit   File: DatabaseMigrator.java   View Source Code Vote up 5 votes
private void migrate4(File dataDir, Stack<Integer> versions) {
	for (File file: dataDir.listFiles()) {
		if (file.getName().startsWith("Accounts.xml")) {
			VersionedDocument dom = VersionedDocument.fromFile(file);
			for (Element element: dom.getRootElement().elements()) {
				Element avatarUploadDateElement = element.element("avatarUploadDate");
				if (avatarUploadDateElement != null)
					avatarUploadDateElement.detach();
			}
			dom.writeToFile(file, false);
		}
	}	
}
 
Example 10
Project: gitplex-mit   File: DefaultPersistManager.java   View Source Code Vote up 5 votes
@Sessional
@Override
public void importData(Metadata metadata, File dataDir) {
	Session session = dao.getSession();
	List<Class<?>> entityTypes = getEntityTypes(sessionFactory);
	Collections.reverse(entityTypes);
	for (Class<?> entityType: entityTypes) {
		File[] dataFiles = dataDir.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				return name.startsWith(entityType.getSimpleName() + "s.xml");
			}
			
		});
		for (File file: dataFiles) {
			try {
				logger.info("Importing from data file '" + file.getName() + "'...");
				session.beginTransaction();
				VersionedDocument dom = VersionedDocument.fromFile(file);
				
				for (Element element: dom.getRootElement().elements()) {
					element.detach();
					AbstractEntity entity = (AbstractEntity) new VersionedDocument(DocumentHelper.createDocument(element)).toBean();
					session.replicate(entity, ReplicationMode.EXCEPTION);
				}
				session.flush();
				session.clear();
				session.getTransaction().commit();
			} catch (Throwable e) {
				session.getTransaction().rollback();
				throw Throwables.propagate(e);
			}
		}
	}	
}
 
Example 11
Project: gitplex-mit   File: DefaultPersistManager.java   View Source Code Vote up 5 votes
protected void validateData(Metadata metadata, File dataDir) {
	List<Class<?>> entityTypes = getEntityTypes(sessionFactory);
	Collections.reverse(entityTypes);
	for (Class<?> entityType: entityTypes) {
		File[] dataFiles = dataDir.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				return name.startsWith(entityType.getSimpleName() + "s.xml");
			}
			
		});
		for (File file: dataFiles) {
			try {
				logger.info("Validating data file '" + file.getName() + "'...");
				VersionedDocument dom = VersionedDocument.fromFile(file);
				
				for (Element element: dom.getRootElement().elements()) {
					element.detach();
					AbstractEntity entity = (AbstractEntity) new VersionedDocument(DocumentHelper.createDocument(element)).toBean();
					validator.validate(entity);
				}
			} catch (Throwable e) {
				throw Throwables.propagate(e);
			}
		}
	}	
}
 
Example 12
Project: Divinity_Original_Sin_2_zhCN   File: DOS2Extract.java   View Source Code Vote up 4 votes
/**
 * 从两个xml中提取增量文本xml
 * 
 * @param document
 * @param documentInc
 * @param autoMaxDiffereceLimit 定义差异度超过 xx % 才会添加到增量文本中
 * @param printAll 是否打印结果
 * @return
 * @throws Exception
 */
@Override
public Document extractIncrement(Document document, Document documentInc,
    int autoMaxDiffereceLimit, boolean print) throws Exception {
  if (autoMaxDiffereceLimit > 0) {
    double f = autoMaxDiffereceLimit * 1.0 / 100.0;
    /**
     * 以第一个文本为比较基准,比较两版汉化文本,输出差异程度
     */
    List<DiffResult> list =
        TextUtils.diff(documentInc, document, documentToMap, true, false, false);
    List<DiffResult> result = new ArrayList<DiffResult>(list.size());
    List<DiffResult> ignore = new ArrayList<DiffResult>(list.size());
    for (DiffResult res : list) {
      if (res.getDifference() >= f) {
        result.add(res);
      } else {
        ignore.add(res);
      }
    }
    /**
     * 根据节点数据,生成增量文本xml
     */
    boolean buildNew = false;
    Document doc = extractIncrement(result, buildNew, print);
    if (print) {
      System.out.println("\n\n----------------------------以下文本低于差异度" + (autoMaxDiffereceLimit)
          + "%不会替换生成增量文本-----------------");
      // 打印不处理的部分
      for (DiffResult nodeResult : ignore) {
        System.out.println(nodeResult.getContentuid() + "="
            + (buildNew ? (nodeResult.getText() + "|" + nodeResult.getNewText())
                : (nodeResult.getNewText() + "|" + nodeResult.getText())));
      }
    }
    return doc;
  }
  Map<String, String> mOri = documentToMap.toMap(document);
  // 获取根节点元素对象
  Element root = documentInc.getRootElement();
  // 子节点
  List<Element> es = root.elements();
  // 使用递归
  Iterator<Element> iterator = es.iterator();
  while (iterator.hasNext()) {
    Element e = iterator.next();
    Attribute attribute = e.attribute("contentuid");
    // System.out.println("属性"+attribute.getName() +":" + attribute.getValue());
    String contentuid = attribute.getValue();
    String newText = e.getText().trim();
    String text = (String) mOri.get(contentuid);
    if (("".equals(text) && "".equals(newText)) || (text.trim().equals(newText))) {
      e.detach();
    } else {
      if (print)
        System.out.println(contentuid + "=" + text + "|" + newText);
    }
  }

  return documentInc;
}