Example usage for org.dom4j Element createCopy

List of usage examples for org.dom4j Element createCopy

Introduction

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

Prototype

Element createCopy();

Source Link

Document

Creates a deep copy of this element The new element is detached from its parent, and getParent() on the clone will return null.

Usage

From source file:com.liferay.alloy.tools.builder.taglib.TagBuilder.java

License:Open Source License

protected Document mergeTlds(Document sourceDoc, Document targetDoc) {
    Element targetRoot = targetDoc.getRootElement();

    DocumentFactory factory = SAXReaderUtil.getDocumentFactory();

    XPath xpathTags = factory.createXPath("//tld:tag");

    Map<String, String> namespaceContextMap = new HashMap<String, String>();

    namespaceContextMap.put(_TLD_XPATH_PREFIX, _TLD_XPATH_URI);

    NamespaceContext namespaceContext = new AlloyGeneratorNamespaceContext(namespaceContextMap);

    xpathTags.setNamespaceContext(namespaceContext);

    List<Node> sources = xpathTags.selectNodes(sourceDoc);

    for (Node source : sources) {
        Element sourceElement = (Element) source;

        String sourceName = sourceElement.elementText("name");

        String xpathTagValue = "//tld:tag[tld:name='" + sourceName + "']";

        XPath xpathTag = factory.createXPath(xpathTagValue);

        xpathTag.setNamespaceContext(namespaceContext);

        List<Node> targets = xpathTag.selectNodes(targetDoc);

        if (targets.size() > 0) {
            Element targetElement = (Element) targets.get(0);

            XPath xpathAttributes = factory.createXPath(xpathTagValue + "//tld:attribute");

            Map<String, String> namespaces = new HashMap<String, String>();

            namespaces.put("tld", StringPool.EMPTY);

            xpathAttributes.setNamespaceURIs(namespaces);

            List<Node> sourceAttributes = xpathAttributes.selectNodes(source);

            for (Node sourceAttribute : sourceAttributes) {
                Element sourceAttributeElement = (Element) sourceAttribute;

                String attributeName = sourceAttributeElement.elementText("name");

                String xpathAttributeValue = "//tld:attribute[tld:name='" + attributeName + "']";

                XPath xpathAttribute = factory.createXPath(xpathTagValue + xpathAttributeValue);

                xpathAttribute.setNamespaceContext(namespaceContext);

                Node targetAttribute = xpathAttribute.selectSingleNode(targetElement);

                if (targetAttribute != null) {
                    targetAttribute.detach();
                }//ww w .  ja v  a 2  s.  c  o m

                targetElement.add(sourceAttributeElement.createCopy());
            }

            Element dynamicAttrElement = targetElement.element("dynamic-attributes");

            if (dynamicAttrElement != null) {
                targetElement.add(dynamicAttrElement.detach());
            }
        } else {
            targetRoot.add(sourceElement.createCopy());
        }
    }

    return targetDoc;
}

From source file:com.liferay.util.xml.XMLConverter.java

License:Open Source License

public static org.w3c.dom.Element toW3CElement(org.dom4j.Element dom4jEl) throws org.dom4j.DocumentException {

    org.dom4j.Document dom4jDoc = org.dom4j.DocumentFactory.getInstance().createDocument();

    dom4jDoc.setRootElement(dom4jEl.createCopy());

    org.w3c.dom.Document w3cDoc = toW3CDocument(dom4jDoc);

    return w3cDoc.getDocumentElement();
}

From source file:com.love320.templateparser.util.ConfigBeanXML.java

License:Apache License

private static Document merger(Document document, Document doc) {
    Iterator documentIter = selectNodes(document, "/beans");//
    if (documentIter.hasNext()) {//
        Element documentElement = (Element) documentIter.next();//?Element

        Iterator dociter = selectNodes(doc, "/beans/bean");//
        while (dociter.hasNext()) {//??
            Element docElement = (Element) dociter.next();//?Element
            deleteElement(document, docElement.attributeValue("id"));//
            documentElement.add(docElement.createCopy());//?,
        }//from   w  ww.j a v  a  2s  . co  m
    }
    return document;
}

From source file:com.orange.atk.atkUI.corecli.reportGenerator.ReportGenerator.java

License:Apache License

/**
 * Create a temporary file which contains only the report part
 * of the security profile.//  w w w .ja  v  a2s  .  co m
 * @throws DocumentException
 */
protected Document getReportPartOfProfile() {
    Document document = profileParser.getDoc();
    Element doElem = (Element) document.getRootElement().selectSingleNode("//do");
    Document documentReport = DocumentHelper.createDocument();
    documentReport.add(doElem.createCopy());
    return documentReport;
}

From source file:com.orange.atk.atkUI.corecli.reportGenerator.resultLink.ResultLink.java

License:Apache License

/**
 * Create <code>Resultvalue</code> object from result element
 * @param elem/*from www . j a v a 2 s .c o  m*/
 * @return the created <code>Resultvalue</code> object.
 */
public static Resultvalue getResultvalue(Element elem, Unmarshaller unmarshaller) {
    String kind = elem.attributeValue("kind");
    Resultvalue resultvalue = null;
    if (kind == null || !kind.equals("use")) {
        Element resultvalueElem = (Element) elem.elements().get(0);
        Document documentResultvalue = DocumentHelper.createDocument();
        documentResultvalue.add(resultvalueElem.createCopy());
        DOMWriter d4Writer = new org.dom4j.io.DOMWriter();
        try {
            org.w3c.dom.Document doc = d4Writer.write(documentResultvalue);
            // Unmarshal the data
            resultvalue = (Resultvalue) unmarshaller.unmarshal(doc);
        } catch (Exception e) {
            Logger.getLogger(ResultLink.class).debug(e);
            e.printStackTrace();
        }
    }
    return resultvalue;
}

From source file:com.stratumsoft.xmlgen.SchemaTypeXmlGenerator.java

License:Open Source License

/**
 * Add the element to the parent branch. The min number of times to add it is determined by the element's minOccurs
 * value and the max no. of times to add it is determined by the minimum of the max repeating elements option
 * and the element's maxOccurs value//from   w  w  w.j a v a  2s .c o  m
 * <p/>
 * Note: the element may again be added multiple times based on its container minOccurs and maxOccurs values
 *
 * @param branch
 * @param elemToAdd
 * @param schElemOfElemToAdd
 */

private void addElement(Branch branch, Element elemToAdd, XmlSchemaElement schElemOfElemToAdd) {

    long minCount = schElemOfElemToAdd.getMinOccurs();
    long maxCount = schElemOfElemToAdd.getMaxOccurs();

    //determine how many times to add this element to the parent
    if (branch != null) {

        if (maxCount > 0) {
            long maxEls = getMaxElementsToGenerate(minCount, maxCount);

            for (long i = 1; i <= maxEls; i++) {
                if (i > minCount) { //anything > the min count but < max is optional
                    if (options.isGenCommentsForParticles()) {
                        branch.add(factory.createComment("optional"));
                    }
                }
                logger.trace("Adding dom4j element: {} to branch: {}", elemToAdd.getName(), branch.getName());
                branch.add(elemToAdd);

                elemToAdd = elemToAdd.createCopy(); //cannot add same element again, so create a copy

                //if id attr is present need to set a new value for it in the copied el
                Attribute idAttr = elemToAdd.attribute("id"); //NON-NLS
                if (idAttr != null) {
                    idAttr.setValue(SampleValueProvider.get(Constants.XSD_ID));
                }
            }
        }
    }

}

From source file:com.thoughtworks.go.server.JUnitReportGenerator.java

License:Apache License

public static void main(String[] args) throws Exception {
    Document doc = new SAXReader().read(new FileInputStream(new File("/home/cruise/sample_junit.xml")));
    Element suite = (Element) doc.selectSingleNode("//testsuite");
    Element rootElement = doc.getRootElement();
    for (int i = 0; i < 50000; i++) {
        Element copy = suite.createCopy();
        setAttr(i, copy, "name");
        setAttr(i, copy, "hostname");
        List<Element> elements = copy.selectNodes(".//testcase");
        for (Element element : elements) {
            setAttr(i, element, "classname");
            setAttr(i, element, "name");
        }/*from   w  w w . ja  v a 2 s .com*/
        rootElement.add(copy);
    }
    FileUtils.writeStringToFile(new File("/tmp/repo/imagine.xml"), doc.asXML(), UTF_8);
}

From source file:com.webarch.common.io.xml.XMLEditor.java

License:Apache License

public boolean save(File outPutFile, Element rootElement, boolean lineAble) {
    final Document document = DocumentFactory.getInstance().createDocument(rootElement.createCopy());
    return save(outPutFile, document, lineAble);
}

From source file:com.webarch.common.io.xml.XMLEditor.java

License:Apache License

private void writeDocument(final OutputStream out, Element rootElement) {
    final Document document = DocumentFactory.getInstance().createDocument(rootElement.createCopy());
    writeDocument(out, document);/*from  www.  ja  va  2  s  .  c om*/

}

From source file:com.webslingerz.jpt.PageTemplateImpl.java

License:Open Source License

AttributesImpl getAttributes(Element element, Expressions expressions) throws PageTemplateException {
    AttributesImpl attributes = new AttributesImpl();
    for (Iterator i = element.attributeIterator(); i.hasNext();) {
        Attribute attribute = (Attribute) i.next();
        Namespace namespace = attribute.getNamespace();
        Namespace elementNamespace = element.getNamespace();
        if (!namespace.hasContent() && elementNamespace.hasContent())
            namespace = elementNamespace;
        // String prefix = namespace.getPrefix();
        // System.err.println( "attribute: name=" + attribute.getName() +
        // "\t" +
        // "qualified name=" + attribute.getQualifiedName() + "\t" +
        // "ns prefix=" + namespace.getPrefix() + "\t" +
        // "ns uri=" + namespace.getURI() );
        // String qualifiedName = attribute.getName();
        // String name = qualifiedName;
        // if ( qualifiedName.startsWith( prefix + ":" ) ) {
        // name = qualifiedName.substring( prefix.length() + 1 );
        // }/*from w  w w.j  a v a 2  s .c  o  m*/
        String name = attribute.getName();

        // Handle JPT attributes
        // if ( prefix.equals( talNamespacePrefix ) ) {
        if (TAL_NAMESPACE_URI.equals(namespace.getURI())
                || (!strict && TAL_NAMESPACE_PREFIX.equals(namespace.getPrefix()))) {

            // tal:define
            if (name.equals("define")) {
                expressions.define = attribute.getValue();
            }

            // tal:condition
            else if (name.equals("condition")) {
                expressions.condition = attribute.getValue();
            }

            // tal:repeat
            else if (name.equals("repeat")) {
                expressions.repeat = attribute.getValue();
            }

            // tal:content
            else if (name.equals("content")) {
                expressions.content = attribute.getValue();
            }

            // tal:replace
            else if (name.equals("replace")) {
                if (expressions.omitTag == null) {
                    expressions.omitTag = "";
                }
                expressions.content = attribute.getValue();
            }

            // tal:attributes
            else if (name.equals("attributes")) {
                expressions.attributes = attribute.getValue();
            }

            // tal:omit-tag
            else if (name.equals("omit-tag")) {
                expressions.omitTag = attribute.getValue();
            }

            // error
            else {
                throw new PageTemplateException("unknown tal attribute: " + name);
            }
        }
        // else if ( prefix.equals( metalNamespacePrefix ) )
        else if (METAL_NAMESPACE_URI.equals(namespace.getURI())
                || (!strict && METAL_NAMESPACE_PREFIX.equals(namespace.getPrefix()))) {

            // metal:use-macro
            if (name.equals("use-macro")) {
                expressions.useMacro = attribute.getValue();
            }

            // metal:define-slot
            else if (name.equals("define-slot")) {
                expressions.defineSlot = attribute.getValue();
            }

            // metal:define-macro
            else if (name.equals("define-macro")) {
                //System.out.println("Defining macro: " + attribute.getValue());
                Element el = element.createCopy();
                el.remove(attribute);
                macros.put(attribute.getValue(), new MacroImpl(el));
                expressions.macro = true;
            }

            // metal:fill-slot
            else if (name.equals("fill-slot")) {
                // these are ignored here, as they don't affect processing
                // of current template, but are called from other templates
            }

            // error
            else {
                throw new PageTemplateException("unknown metal attribute: " + name);
            }
        }

        // Pass on all other attributes
        else {
            String nsURI = namespace.getURI();
            // String qualifiedName = namespace.getPrefix() + ":" + name;
            attributes.addAttribute(nsURI, name, attribute.getQualifiedName(), "CDATA", attribute.getValue());
            if (nsURI != "" && namespace != elementNamespace) {
                String prefix = namespace.getPrefix();
                String qName = "xmlns:" + prefix;
                if (attributes.getIndex(qName) == -1) {
                    // add xmlns for this attribute
                    attributes.addAttribute("", prefix, qName, "CDATA", nsURI);
                }
            }
            // attributes.addAttribute( getNamespaceURIFromPrefix(prefix),
            // name, qualifiedName, "CDATA", attribute.getValue() );
        }
    }
    return attributes;
}