Example usage for org.w3c.dom Element getOwnerDocument

List of usage examples for org.w3c.dom Element getOwnerDocument

Introduction

In this page you can find the example usage for org.w3c.dom Element getOwnerDocument.

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

From source file:org.dhatim.templating.xslt.XslTemplateProcessor.java

@Override
protected void visit(Element element, ExecutionContext executionContext) throws SmooksException {
    Document ownerDoc = element.getOwnerDocument();
    Element ghostElement = GhostElementSerializationUnit.createElement(ownerDoc);

    try {//w ww  .jav  a  2 s  .co  m
        if (isSynchronized) {
            synchronized (xslTemplate) {
                performTransform(element, ghostElement, ownerDoc);
            }
        } else {
            performTransform(element, ghostElement, ownerDoc);
        }
    } catch (TransformerException e) {
        throw new SmooksException("Error applying XSLT to node [" + executionContext.getDocumentSource() + ":"
                + DomUtils.getXPath(element) + "]", e);
    }

    if (getOutputStreamResource() != null || getAction() == Action.BIND_TO) {
        // For bindTo or streamTo actions, we need to serialize the content and supply is as a Text DOM node.
        // AbstractTemplateProcessor will look after the rest, by extracting the content from the
        // Text node and attaching it to the ExecutionContext...
        String serializedContent = XmlUtil.serialize(ghostElement.getChildNodes());
        Text textNode = element.getOwnerDocument().createTextNode(serializedContent);

        processTemplateAction(element, textNode, executionContext);
    } else {
        NodeList children = ghostElement.getChildNodes();

        // Process the templating action, supplying the templating result...
        if (children.getLength() == 1 && children.item(0).getNodeType() == Node.ELEMENT_NODE) {
            processTemplateAction(element, children.item(0), executionContext);
        } else {
            processTemplateAction(element, ghostElement, executionContext);
        }
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Rename element.//from w  w  w . jav  a 2 s.  co  m
 * @param element The element to be renamed.
 * @param replacementElement The tag name of the replacement element.  Can be a prefix qualified
  * name if the namespace is not the null namepsace ({@link javax.xml.XMLConstants#NULL_NS_URI}).
  * @param namespace The element namespace.
 * @param keepChildContent <code>true</code> if the target element's child content
 * is to be copied to the replacement element, false if not. Default <code>true</code>.
 * @param keepAttributes <code>true</code> if the target element's attributes
 * are to be copied to the replacement element, false if not. Default <code>true</code>.
 * @return The renamed element.
 */
public static Element renameElementNS(Element element, String replacementElement, String namespace,
        boolean keepChildContent, boolean keepAttributes) {
    AssertArgument.isNotNull(element, "element");
    AssertArgument.isNotNull(replacementElement, "replacementElement");

    Element replacement;
    if (namespace != null && !XMLConstants.NULL_NS_URI.equals(namespace)) {
        replacement = element.getOwnerDocument().createElementNS(namespace, replacementElement);
    } else {
        replacement = element.getOwnerDocument().createElement(replacementElement);
    }

    if (keepChildContent) {
        DomUtils.copyChildNodes(element, replacement);
    }
    if (keepAttributes) {
        NamedNodeMap attributes = element.getAttributes();
        int attributeCount = attributes.getLength();

        for (int i = 0; i < attributeCount; i++) {
            Attr attribute = (Attr) attributes.item(i);
            replacement.setAttribute(attribute.getName(), attribute.getValue());
        }
    }
    DomUtils.replaceNode(replacement, element);

    return replacement;
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Add literal text to the supplied element.
 * @param element Target DOM Element./*  w w w. ja  v a  2 s . c o m*/
 * @param literalText Literal text to be added.
 */
public static void addLiteral(Element element, String literalText) {
    AssertArgument.isNotNull(element, "element");
    AssertArgument.isNotNull(literalText, "literalText");

    Document document = element.getOwnerDocument();
    Text literal = document.createTextNode(literalText);
    element.appendChild(literal);
}

From source file:org.dita.dost.module.BranchFilterModule.java

private void filterBranches(final Element elem, final List<FilterUtils> filters, final QName[][] props) {
    final List<FilterUtils> fs = combineFilterUtils(elem, filters);

    boolean exclude = false;
    for (final FilterUtils f : fs) {
        exclude = f.needExclude(elem, props);
        if (exclude) {
            break;
        }//  w w w . j  a v  a  2  s  .  c  om
    }

    if (exclude) {
        elem.getParentNode().removeChild(elem);
    } else {
        final List<Element> childElements = getChildElements(elem);
        final Set<Flag> flags = fs.stream().flatMap(f -> f.getFlags(elem, props).stream())
                .map(f -> f.adjustPath(currentFile, job)).collect(Collectors.toSet());
        for (Flag flag : flags) {
            final Element startElement = (Element) elem.getOwnerDocument().importNode(flag.getStartFlag(),
                    true);
            final Node firstChild = elem.getFirstChild();
            if (firstChild != null) {
                elem.insertBefore(startElement, firstChild);
            } else {
                elem.appendChild(startElement);
            }
            final Element endElement = (Element) elem.getOwnerDocument().importNode(flag.getEndFlag(), true);
            elem.appendChild(endElement);
        }
        for (final Element child : childElements) {
            filterBranches(child, fs, props);
        }
    }
}

From source file:org.dita.dost.reader.ChunkMapReader.java

/**
 * Create new map and refer to it with navref.
 * @param topicref//from w w w . j av a  2s  .co m
 */
private void processNavitation(final Element topicref) {
    // create new map's root element
    final Element root = (Element) topicref.getOwnerDocument().getDocumentElement().cloneNode(false);
    // create navref element
    final Element navref = topicref.getOwnerDocument().createElement(MAP_NAVREF.localName);
    final String newMapFile = chunkFilenameGenerator.generateFilename("MAPCHUNK", FILE_EXTENSION_DITAMAP);
    navref.setAttribute(ATTRIBUTE_NAME_MAPREF, newMapFile);
    navref.setAttribute(ATTRIBUTE_NAME_CLASS, MAP_NAVREF.toString());
    // replace topicref with navref
    topicref.getParentNode().replaceChild(navref, topicref);
    root.appendChild(topicref);
    // generate new file
    final File navmap = resolve(fileDir, newMapFile);
    changeTable.put(navmap.getPath(), navmap.getPath());
    outputMapFile(navmap, buildOutputDocument(root));
}

From source file:org.dita.dost.writer.ConrefPushParser.java

/**
 * /*ww w .  j  a  v  a 2 s  . c  o  m*/
 * @param targetClassAttribute targetClassAttribute
 * @param content string
 * @return string
 */
private DocumentFragment replaceElementName(final DitaClass targetClassAttribute,
        final DocumentFragment content) {
    try {
        if (content.hasChildNodes()) {
            final NodeList nodeList = content.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                final Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    final Element elem = (Element) node;
                    final DitaClass clazz = DitaClass.getInstance(elem);
                    // get type of the target element
                    final String type = targetClassAttribute.toString()
                            .substring(1, targetClassAttribute.toString().indexOf("/")).trim();
                    if (!clazz.equals(targetClassAttribute) && targetClassAttribute.matches(clazz)) {
                        // Specializing the pushing content is not handled here
                        // but we can catch such a situation to emit a warning by comparing the class values.
                        final String targetElementName = targetClassAttribute.toString()
                                .substring(targetClassAttribute.toString().indexOf("/") + 1).trim();
                        if (elem.getAttributeNode(ATTRIBUTE_NAME_CONREF) != null) {
                            hasConref = true;
                        }
                        if (elem.getAttributeNode(ATTRIBUTE_NAME_KEYREF) != null) {
                            hasKeyref = true;
                        }
                        elem.getOwnerDocument().renameNode(elem, elem.getNamespaceURI(), targetElementName);
                        // process the child nodes of the current node
                        final NodeList nList = elem.getChildNodes();
                        for (int j = 0; j < nList.getLength(); j++) {
                            final Node subNode = nList.item(j);
                            if (subNode.getNodeType() == Node.ELEMENT_NODE) {
                                //replace the subElement Name
                                replaceSubElementName(type, (Element) subNode);
                            }
                        }
                    } else {
                        replaceSubElementName(STRING_BLANK, elem);
                    }
                }
            }
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return content;
}

From source file:org.dita.dost.writer.ConrefPushParser.java

/**
 * //w w  w. j  a v a 2  s  . co  m
 * @param type pushtype
 * @param elem element
 * @return string
 */
private void replaceSubElementName(final String type, final Element elem) {
    final DitaClass classValue = DitaClass.getInstance(elem);
    if (elem.getAttributeNode(ATTRIBUTE_NAME_CONREF) != null) {
        hasConref = true;
    }
    if (elem.getAttributeNode(ATTRIBUTE_NAME_KEYREF) != null) {
        hasKeyref = true;
    }
    String generalizedElemName = elem.getNodeName();
    if (classValue != null) {
        if (classValue.toString().contains(type) && !type.equals(STRING_BLANK)) {
            generalizedElemName = classValue.toString()
                    .substring(classValue.toString().indexOf("/") + 1,
                            classValue.toString().indexOf(STRING_BLANK, classValue.toString().indexOf("/")))
                    .trim();
        }
    }
    elem.getOwnerDocument().renameNode(elem, elem.getNamespaceURI(), generalizedElemName);
    final NodeList nodeList = elem.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            replaceSubElementName(type, (Element) node);
        }
    }
}

From source file:org.docx4j.fonts.fop.fonts.apps.TTFReader.java

private void generateDOM4MultiByteExtras(Element parent, TTFFile ttf, boolean isCid) {
    Element el;/*from ww w .j a va2s .  c  o  m*/
    Document doc = parent.getOwnerDocument();

    Element mel = doc.createElement("multibyte-extras");
    parent.appendChild(mel);

    el = doc.createElement("cid-type");
    mel.appendChild(el);
    el.appendChild(doc.createTextNode("CIDFontType2"));

    el = doc.createElement("default-width");
    mel.appendChild(el);
    el.appendChild(doc.createTextNode("0"));

    el = doc.createElement("bfranges");
    mel.appendChild(el);
    Iterator iter = ttf.getCMaps().listIterator();
    while (iter.hasNext()) {
        TTFCmapEntry ce = (TTFCmapEntry) iter.next();
        Element el2 = doc.createElement("bf");
        el.appendChild(el2);
        el2.setAttribute("us", String.valueOf(ce.getUnicodeStart()));
        el2.setAttribute("ue", String.valueOf(ce.getUnicodeEnd()));
        el2.setAttribute("gi", String.valueOf(ce.getGlyphStartIndex()));
    }

    el = doc.createElement("cid-widths");
    el.setAttribute("start-index", "0");
    mel.appendChild(el);

    int[] wx = ttf.getWidths();
    for (int i = 0; i < wx.length; i++) {
        Element wxel = doc.createElement("wx");
        wxel.setAttribute("w", String.valueOf(wx[i]));
        el.appendChild(wxel);
    }
}

From source file:org.docx4j.openpackaging.parts.JaxbXmlPart.java

public E unmarshal(org.w3c.dom.Element el) throws JAXBException {

    try {//from www  . jav a  2s.com

        Unmarshaller u = jc.createUnmarshaller();
        JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler();
        eventHandler.setContinue(false);
        u.setEventHandler(eventHandler);

        try {
            jaxbElement = (E) XmlUtils.unwrap(u.unmarshal(el));
        } catch (UnmarshalException ue) {
            log.info("encountered unexpected content; pre-processing");
            try {
                org.w3c.dom.Document doc;
                if (el instanceof org.w3c.dom.Document) {
                    doc = (org.w3c.dom.Document) el;
                } else {
                    // Hope for the best. Dodgy though; what if this is
                    // being used on something deep in the tree?
                    // TODO: revisit
                    doc = el.getOwnerDocument();
                }
                eventHandler.setContinue(true);
                JAXBResult result = XmlUtils.prepareJAXBResult(jc);
                Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor();
                XmlUtils.transform(doc, mcPreprocessorXslt, null, result);
                jaxbElement = (E) XmlUtils.unwrap(result.getResult());
            } catch (Exception e) {
                throw new JAXBException("Preprocessing exception", e);
            }
        }
        return jaxbElement;

    } catch (JAXBException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}

From source file:org.docx4j.openpackaging.parts.JaxbXmlPartXPathAware.java

/**
 * @since 2.7.1//from  w w w  . j a v  a  2 s .  co m
 */
@Override
public E unmarshal(org.w3c.dom.Element el) throws JAXBException {

    try {
        log.debug("For " + this.getClass().getName() + ", unmarshall via binder");

        binder = jc.createBinder();
        JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler();
        eventHandler.setContinue(false);
        binder.setEventHandler(eventHandler);

        try {
            //            jaxbElement =  (E) XmlUtils.unwrap(binder.unmarshal( el ));
            unwrapUsually(binder, el); // unlikely to need this in the code below

        } catch (Exception ue) {
            if (ue instanceof UnmarshalException) {
                // Usually..
            } else {
                // eg java.lang.NumberFormatException
                log.warn(ue.getMessage(), ue);
                log.info(".. can recover if problem is w:tblW/@w:w");
            }
            log.info("encountered unexpected content; pre-processing");
            org.w3c.dom.Document doc = null;
            try {
                if (el instanceof org.w3c.dom.Document) {
                    doc = (org.w3c.dom.Document) el;
                } else {
                    // Hope for the best. Dodgy though; what if this is
                    // being used on something deep in the tree?
                    // TODO: revisit
                    doc = el.getOwnerDocument();
                }
                eventHandler.setContinue(true);
                DOMResult result = new DOMResult();
                Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor();
                XmlUtils.transform(doc, mcPreprocessorXslt, null, result);
                doc = (org.w3c.dom.Document) result.getNode();
                jaxbElement = (E) XmlUtils.unwrap(binder.unmarshal(doc));
            } catch (ClassCastException cce) {
                log.warn("Binder not available for this docx");
                Unmarshaller u = jc.createUnmarshaller();
                jaxbElement = (E) XmlUtils.unwrap(u.unmarshal(doc));
            } catch (Exception e) {
                throw new JAXBException("Preprocessing exception", e);
            }
        }
        return jaxbElement;

    } catch (JAXBException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}