Example usage for org.dom4j Element remove

List of usage examples for org.dom4j Element remove

Introduction

In this page you can find the example usage for org.dom4j Element remove.

Prototype

boolean remove(Text text);

Source Link

Document

Removes the given Text if the node is an immediate child of this element.

Usage

From source file:com.globalsight.cxe.adapter.msoffice.WordRepairer.java

License:Apache License

/**
 * For GBS-3085./*from  w  w  w . j  av a2  s  .com*/
 */
@SuppressWarnings("unchecked")
private static void forHyperlinkInWt(Element element) {
    List<Node> ts = element.selectNodes("//w:r/w:t/w:hyperlink/w:r");

    boolean find = false;

    for (Node t : ts) {
        find = true;
        Element hyperlink = t.getParent();

        if (hyperlink == null)
            continue;

        Element wt = hyperlink.getParent();
        if (wt == null)
            continue;

        Element wr = wt.getParent();
        if (wr == null)
            continue;

        Element wrParent = wr.getParent();
        if (wrParent == null)
            continue;

        List wtNodes = wt.content();
        List removedNodes = new ArrayList();

        int index = wtNodes.indexOf(hyperlink);
        for (int i = wtNodes.size() - 1; i >= index; i--) {
            removedNodes.add(0, wtNodes.remove(i));
        }

        Element cloneWr = (Element) wr.clone();
        List es = wrParent.content();
        index = es.indexOf(wr);

        wrParent.remove(cloneWr);
        es.add(index, cloneWr);
        es.add(index + 1, hyperlink);

        wt.clearContent();
        List wts = wt.content();
        for (int i = 1; i < removedNodes.size(); i++) {
            wts.add(removedNodes.get(i));
        }
    }

    if (find) {
        forHyperlinkInWt(element);
    }
}

From source file:com.globalsight.cxe.adapter.msoffice.WordRepairer.java

License:Apache License

private static void forNodesInWt(Element element) {
    @SuppressWarnings("unchecked")
    List<Element> wts = element.selectNodes("//w:t");

    for (Element wt : wts) {
        @SuppressWarnings("unchecked")
        List<Element> es = wt.elements();

        if (!wt.isTextOnly()) {
            String text = wt.getStringValue();
            for (Element e : es) {
                wt.remove(e);
            }/* w  w w .  j  a  v a  2s.com*/

            wt.setText(text);
        }
    }
}

From source file:com.globalsight.cxe.adapter.msoffice.WordRepairer.java

License:Apache License

private static void forWrInWr(Element element) {
    @SuppressWarnings("unchecked")
    List<Node> ts = element.selectNodes("//w:r/w:r");

    for (Node t : ts) {
        Element wr = t.getParent();

        if (wr == null)
            continue;

        List<?> els = wr.content();

        StringBuffer sb = new StringBuffer();
        Element wt = null;/* www.  j  a v a  2s  .c  o  m*/
        List<Element> wrs = new ArrayList<Element>();

        for (Object el : els) {
            if (el instanceof Element) {
                Element elm = (Element) el;
                if ("t".equals(elm.getName())) {
                    wt = elm;
                    sb.append(elm.getStringValue());
                } else if ("r".equals(elm.getName())) {
                    sb.append(elm.getStringValue());
                    wrs.add(elm);
                }
            }
        }

        if (wt == null) {
            wt = wr.addElement("w:t");
            wt.addAttribute("xml:space", "preserve");
        }

        wt.setText(sb.toString());

        for (Element w : wrs) {
            wr.remove(w);
        }
    }
}

From source file:com.globalsight.cxe.adapter.msoffice.WordRepairer.java

License:Apache License

private static void forWtNotInWr(Element element) {
    @SuppressWarnings("unchecked")
    List<Element> wts = element.selectNodes("//w:t");

    for (Element wt : wts) {
        Element parent = wt.getParent();
        if (parent == null || "r".equals(parent.getName()))
            continue;

        @SuppressWarnings("unchecked")
        List<Element> es = parent.elements();

        int wtIndex = -1;
        for (Element e : es) {
            wtIndex++;//from w ww . jav a2s.co m
            if (wt.equals(e)) {
                break;
            }
        }

        for (int i = 1; i < es.size(); i++) {
            int prefix = wtIndex - i;
            int suffix = wtIndex + i;

            if (prefix < 0 && suffix > es.size() - 1) {
                break;
            }

            if (prefix > -1) {
                Element prefixElement = es.get(prefix);
                if ("r".equals(prefixElement.getName())) {
                    @SuppressWarnings("unchecked")
                    List<Element> preWts = prefixElement.elements("t");

                    if (preWts.size() > 0) {
                        String text = wt.getStringValue();
                        Element preWt = preWts.get(preWts.size() - 1);
                        preWt.setText(preWt.getStringValue() + text);
                        parent.remove(wt);
                        break;
                    }
                }
            }

            if (suffix < es.size()) {
                Element sufixElement = es.get(prefix);
                if ("r".equals(sufixElement.getName())) {
                    @SuppressWarnings("unchecked")
                    List<Element> sufWts = sufixElement.elements("t");

                    if (sufWts.size() > 0) {
                        String text = wt.getStringValue();
                        Element sufWt = sufWts.get(0);
                        sufWt.setText(text + sufWt.getStringValue());
                        parent.remove(wt);
                        break;
                    }
                }
            }
        }
    }
}

From source file:com.globalsight.cxe.adapter.msoffice.WordRepairer.java

License:Apache License

private static void forTextInWr(Element element) {
    @SuppressWarnings("unchecked")
    List<Node> ts = element.selectNodes("//w:r/text()");

    for (Node t : ts) {
        if (t.getText().matches("[\n\r]*")) {
            continue;
        }/*  w ww. j  a v a2s . co  m*/

        Element wr = t.getParent();

        if (wr == null) {
            continue;
        }

        List<?> els = wr.content();

        StringBuffer sb = new StringBuffer();
        Element wt = null;
        List<DefaultText> texts = new ArrayList<DefaultText>();

        for (Object el : els) {
            if (el instanceof DefaultText) {
                DefaultText text = (DefaultText) el;
                texts.add(text);
                sb.append(text.getStringValue());
            } else if (el instanceof Element) {
                Element elm = (Element) el;
                if ("t".equals(elm.getName())) {
                    wt = elm;
                    sb.append(elm.getStringValue());
                }
            }
        }

        if (wt == null) {
            wt = wr.addElement("w:t");
            wt.addAttribute("xml:space", "preserve");
        }

        wt.setText(sb.toString());

        for (DefaultText text : texts) {
            wr.remove(text);
        }
    }
}

From source file:com.globalsight.cxe.adapter.msoffice.WordRepairer.java

License:Apache License

private static void forTextInWp(Element element) {
    @SuppressWarnings("unchecked")
    List<Node> ts = element.selectNodes("//w:p/text()");

    for (Node t : ts) {
        String c = t.getText();// w ww .  ja  v a  2s . c  o  m
        if (c.matches("[\n\r]*")) {
            continue;
        }

        Element wp = t.getParent();
        Element wr = DocumentHelper.createElement("w:r");
        wp.content().add(wp.indexOf(t), wr);
        Element wt = wr.addElement("w:t");
        wt.setText(t.getText());
        wp.remove(t);
    }
}

From source file:com.globalsight.everest.edit.offline.OfflineEditManagerLocal.java

License:Apache License

/**
 * Only when the source file is XLF, need re-wrap the off-line down-loaded
 * XLIFF file./*from w w w  .  j  av  a  2  s.  co  m*/
 */
private void reWrapXliff(Document doc, HashSet<Long> jobIds) {
    Element root = doc.getRootElement();
    Element bodyElement = root.element(XliffConstants.FILE).element(XliffConstants.BODY);

    // Find TU elements that are from XLF source file.
    List<Element> xlfTuElements = new ArrayList<Element>();
    for (Iterator i = bodyElement.elementIterator(XliffConstants.TRANS_UNIT); i.hasNext();) {
        Element foo = (org.dom4j.Element) i.next();
        if (isSrcFileXlf(foo, jobIds)) {
            xlfTuElements.add(foo);
        }
    }

    if (xlfTuElements.size() == 0)
        return;

    //
    StringBuffer xliffString = new StringBuffer();
    xliffString.append("<?xml version=\"1.0\"?>");
    xliffString.append("<xliff version=\"1.2\">");
    xliffString.append("<file>");
    xliffString.append("<body>");
    Attribute stateAttr = null;
    ArrayList<String> trgStates = new ArrayList<String>();
    for (Element foo : xlfTuElements) {
        Element sourceElement = foo.element(XliffConstants.SOURCE);
        String sourceContent = sourceElement.asXML();
        sourceContent = sourceContent.replaceFirst("<" + XliffConstants.SOURCE + "[^>]*>", "");
        sourceContent = sourceContent.replace("</" + XliffConstants.SOURCE + ">", "");

        Element targetElement = foo.element(XliffConstants.TARGET);

        String targetContent = targetElement.asXML();
        targetContent = targetContent.replaceFirst("<" + XliffConstants.TARGET + "[^>]*>", "");
        targetContent = targetContent.replace("</" + XliffConstants.TARGET + ">", "");

        xliffString.append("<trans-unit>");
        xliffString.append("<source>").append(sourceContent).append("</source>");
        xliffString.append("<target>").append(targetContent).append("</target>");
        xliffString.append("</trans-unit>");

        // Store the state attributes in sequence
        stateAttr = targetElement.attribute(XliffConstants.STATE);
        if (stateAttr == null) {
            trgStates.add("");
        } else {
            trgStates.add(stateAttr.getValue());
        }
    }
    xliffString.append("</body>");
    xliffString.append("</file>");
    xliffString.append("</xliff>");

    // Extract it to get re-wrapped segments.
    DiplomatAPI api = new DiplomatAPI();
    api.setEncoding("UTF-8");
    api.setLocale(new Locale("en_US"));
    api.setInputFormat("xlf");
    api.setSentenceSegmentation(false);
    api.setSegmenterPreserveWhitespace(true);
    api.setSourceString(xliffString.toString());

    ArrayList<String> sourceArray = new ArrayList<String>();
    ArrayList<String> targetArray = new ArrayList<String>();

    try {
        api.extract();
        Output output = api.getOutput();

        for (Iterator it = output.documentElementIterator(); it.hasNext();) {
            DocumentElement element = (DocumentElement) it.next();

            if (element instanceof TranslatableElement) {
                TranslatableElement trans = (TranslatableElement) element;

                SegmentNode src = (SegmentNode) (trans.getSegments().get(0));
                if (trans.getXliffPartByName().equals("source")) {
                    sourceArray.add("<source>" + replaceEntity(src.getSegment()) + "</source>");
                } else if (trans.getXliffPartByName().equals("target")) {
                    targetArray.add("<target>" + replaceEntity(src.getSegment()) + "</target>");
                }
            }
        }
    } catch (Exception e) {
        if (s_category.isDebugEnabled()) {
            s_category.error(e.getMessage(), e);
        }
    }

    // Replace source/target elements
    int index = 0;
    if (sourceArray != null && targetArray != null) {
        for (Iterator i = bodyElement.elementIterator(XliffConstants.TRANS_UNIT); i.hasNext();) {
            if (index >= sourceArray.size()) {
                break;
            }

            Element foo = (org.dom4j.Element) i.next();
            if (!isSrcFileXlf(foo, jobIds)) {
                continue;
            }

            TuImpl tu = getTu(foo, jobIds);
            GxmlElement srcGxmlElement = tu.getSourceTuv().getGxmlElement();
            String newSrc = "<segment>" + GxmlUtil.stripRootTag(sourceArray.get(index)) + "</segment>";
            GxmlElement trgGxmlElement = SegmentUtil2.getGxmlElement(newSrc);
            newSrc = SegmentUtil2.adjustSegmentAttributeValues(srcGxmlElement, trgGxmlElement, "xlf");
            newSrc = "<source>" + GxmlUtil.stripRootTag(newSrc) + "</source>";
            Element sourceElement = foo.element(XliffConstants.SOURCE);
            Element newSourceElement = getDom(newSrc).getRootElement();
            foo.remove(sourceElement);
            foo.add(newSourceElement);

            String newTrg = "<segment>" + GxmlUtil.stripRootTag(targetArray.get(index)) + "</segment>";
            trgGxmlElement = SegmentUtil2.getGxmlElement(newTrg);
            newTrg = SegmentUtil2.adjustSegmentAttributeValues(srcGxmlElement, trgGxmlElement, "xlf");
            newTrg = "<target>" + GxmlUtil.stripRootTag(newTrg) + "</target>";
            Element newTargetElement = getDom(newTrg).getRootElement();
            Element targetElement = foo.element(XliffConstants.TARGET);
            foo.remove(targetElement);
            // If target has "state" attribute, it should be preserved.
            try {
                if (!"".equals(trgStates.get(index))) {
                    newTargetElement.add(new DefaultAttribute(XliffConstants.STATE, trgStates.get(index)));
                }
            } catch (Exception ignore) {

            }

            foo.add(newTargetElement);
            index++;
        }
    }
}

From source file:com.globalsight.everest.edit.offline.page.TmxUtil.java

License:Apache License

private static void removeAttributeForNode(Element root, String nodeName, String[] attributes) {
    List elements = root.elements(nodeName);
    Iterator it = elements.iterator();
    while (it.hasNext()) {
        Element element = (Element) it.next();
        for (int i = 0; i < attributes.length; i++) {
            Attribute attribute = element.attribute(attributes[i]);
            if (attribute != null) {
                element.remove(element.attribute(attributes[i]));
            }/*from  ww  w.j  av a  2 s . c  o m*/
        }
    }
}

From source file:com.globalsight.everest.edit.offline.page.TmxUtil.java

License:Apache License

private static void removeUncompliantAttributes(Element root, String[] attributes) {
    List elements = root.elements();
    Iterator it = elements.iterator();
    while (it.hasNext()) {
        Element element = (Element) it.next();
        for (int i = 0; i < attributes.length; i++) {
            Attribute attribute = element.attribute(attributes[i]);
            if (attribute != null) {
                element.remove(element.attribute(attributes[i]));
            }//from   w  w  w  .jav a  2 s  .  c om
        }
    }
}

From source file:com.globalsight.everest.tm.exporter.TmxChecker.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
public String fixSegment(String segment) {
    Document dom = getDom(segment);
    Element root = dom.getRootElement();

    Iterator ite = dtdMap.entrySet().iterator();
    while (ite.hasNext()) {
        Map.Entry entry = (Map.Entry) ite.next();
        String key = (String) entry.getKey();
        ArrayList array = (ArrayList) entry.getValue();

        String nodeName = "//" + key;
        List nodes = root.selectNodes(nodeName);

        for (int x = 0; x < nodes.size(); x++) {
            Element node = (Element) nodes.get(x);
            Attribute internalAttr = node.attribute("internal");
            Attribute typeAttr = node.attribute("type");
            ArrayList list = new ArrayList();
            list.addAll(node.attributes());
            resetXAttribute(key, list);/*from   w  ww  . j  a  v a 2 s. c o m*/

            for (int y = 0; y < list.size(); y++) {
                Attribute temp = (Attribute) list.get(y);
                String name = temp.getName();

                if (!array.contains(name)) {
                    node.remove(temp);
                }
            }
            // GBS-3537 & GBS-3691
            if (internalAttr != null && "yes".equalsIgnoreCase(internalAttr.getValue())) {
                String exportedType = "x-internal";
                if (typeAttr != null) {
                    String type = typeAttr.getValue();
                    if (StringUtil.isNotEmpty(type)) {
                        exportedType += "-" + type.trim().toLowerCase();
                    }
                    typeAttr.setValue(exportedType);
                } else {
                    node.add(new DefaultAttribute("type", exportedType));
                }
            }
        }
    }

    return root.asXML();
}