Example usage for org.w3c.dom Node getOwnerDocument

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

Introduction

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

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

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

/**
 * Set the value of the node referenced in the xpath expression.
 * // w  w  w .j a va 2  s.  com
 * @param xpath
 * @param value
 * @param prefixMappings a string such as "xmlns:ns0='http://schemas.medchart'"
 * @return
 * @throws Docx4JException
 */
public boolean setNodeValueAtXPath(String xpath, String value, String prefixMappings) throws Docx4JException {

    try {
        getNamespaceContext().registerPrefixMappings(prefixMappings);

        Node n = (Node) xPath.evaluate(xpath, doc, XPathConstants.NODE);
        if (n == null) {
            log.debug("xpath returned null");
            return false;
        }
        log.debug(n.getClass().getName());

        // Method 1: Crimson throws error
        // Could avoid with System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
        //       "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        //n.setTextContent(value);

        // Method 2: crimson ignores
        // n.setNodeValue(value);

        // Method 3: createTextNode, then append it
        // First, need to delete/replace existing text node 
        if (n.getChildNodes() != null && n.getChildNodes().getLength() > 0) {
            NodeList nodes = n.getChildNodes();
            for (int i = nodes.getLength(); i > 0; i--) {
                n.removeChild(nodes.item(i - 1));
            }
        }
        Text t = n.getOwnerDocument().createTextNode(value);
        n.appendChild(t);

        // cache is now invalid
        return true;
    } catch (Exception e) {
        throw new Docx4JException("Problem setting value at xpath " + xpath);
    }

}

From source file:org.docx4j.XmlUtils.java

/**
 * Copy a node from one DOM document to another.  Used
 * to avoid relying on an underlying implementation which might 
 * not support importNode //from   ww  w.  j a va 2  s.com
 * (eg Xalan's org.apache.xml.dtm.ref.DTMNodeProxy).
 * 
 * WARNING: doesn't fully support namespaces!
 * 
 * @param sourceNode
 * @param destParent
 */
public static void treeCopy(Node sourceNode, Node destParent) {

    // http://osdir.com/ml/text.xml.xerces-j.devel/2004-04/msg00066.html
    // suggests the problem has been fixed?

    // source node maybe org.apache.xml.dtm.ref.DTMNodeProxy
    // (if its xslt output we are copying)
    // or com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl
    // (if its marshalled JAXB)

    log.debug("node type" + sourceNode.getNodeType());

    switch (sourceNode.getNodeType()) {

    case Node.DOCUMENT_NODE: // type 9
    case Node.DOCUMENT_FRAGMENT_NODE: // type 11

        //              log.debug("DOCUMENT:" + w3CDomNodeToString(sourceNode) );
        //              if (sourceNode.getChildNodes().getLength()==0) {
        //                 log.debug("..no children!");
        //              }

        // recurse on each child
        NodeList nodes = sourceNode.getChildNodes();
        if (nodes != null) {
            for (int i = 0; i < nodes.getLength(); i++) {
                log.debug("child " + i + "of DOCUMENT_NODE");
                //treeCopy((DTMNodeProxy)nodes.item(i), destParent);
                treeCopy((Node) nodes.item(i), destParent);
            }
        }
        break;
    case Node.ELEMENT_NODE:

        // Copy of the node itself
        log.debug("copying: " + sourceNode.getNodeName());
        Node newChild;
        if (destParent instanceof Document) {
            newChild = ((Document) destParent).createElementNS(sourceNode.getNamespaceURI(),
                    sourceNode.getLocalName());
        } else if (sourceNode.getNamespaceURI() != null) {
            newChild = destParent.getOwnerDocument().createElementNS(sourceNode.getNamespaceURI(),
                    sourceNode.getLocalName());
        } else {
            newChild = destParent.getOwnerDocument().createElement(sourceNode.getNodeName());
        }
        destParent.appendChild(newChild);

        // .. its attributes
        NamedNodeMap atts = sourceNode.getAttributes();
        for (int i = 0; i < atts.getLength(); i++) {

            Attr attr = (Attr) atts.item(i);

            //                  log.debug("attr.getNodeName(): " + attr.getNodeName());
            //                  log.debug("attr.getNamespaceURI(): " + attr.getNamespaceURI());
            //                  log.debug("attr.getLocalName(): " + attr.getLocalName());
            //                  log.debug("attr.getPrefix(): " + attr.getPrefix());

            if (attr.getNodeName().startsWith("xmlns:")) {
                /* A document created from a dom4j document using dom4j 1.6.1's io.domWriter
                 does this ?!
                 attr.getNodeName(): xmlns:w 
                 attr.getNamespaceURI(): null
                 attr.getLocalName(): null
                 attr.getPrefix(): null
                         
                 unless i'm doing something wrong, this is another reason to
                 remove use of dom4j from docx4j
                */
                ;
                // this is a namespace declaration. not our problem
            } else if (attr.getNamespaceURI() == null) {
                //log.debug("attr.getLocalName(): " + attr.getLocalName() + "=" + attr.getValue());
                ((org.w3c.dom.Element) newChild).setAttribute(attr.getName(), attr.getValue());
            } else if (attr.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/")) {
                ; // this is a namespace declaration. not our problem
            } else if (attr.getNodeName() != null) {
                // && attr.getNodeName().equals("xml:space")) {
                // restrict this fix to xml:space only, if necessary

                // Necessary when invoked from BindingTraverserXSLT,
                // com.sun.org.apache.xerces.internal.dom.AttrNSImpl
                // otherwise it was becoming w:space="preserve"!

                /* eg xml:space
                 * 
                   attr.getNodeName(): xml:space
                   attr.getNamespaceURI(): http://www.w3.org/XML/1998/namespace
                   attr.getLocalName(): space
                   attr.getPrefix(): xml
                 */

                ((org.w3c.dom.Element) newChild).setAttributeNS(attr.getNamespaceURI(), attr.getNodeName(),
                        attr.getValue());
            } else {
                ((org.w3c.dom.Element) newChild).setAttributeNS(attr.getNamespaceURI(), attr.getLocalName(),
                        attr.getValue());
            }
        }

        // recurse on each child
        NodeList children = sourceNode.getChildNodes();
        if (children != null) {
            for (int i = 0; i < children.getLength(); i++) {
                //treeCopy( (DTMNodeProxy)children.item(i), newChild);
                treeCopy((Node) children.item(i), newChild);
            }
        }

        break;

    case Node.TEXT_NODE:

        // Where destParent is com.sun.org.apache.xerces.internal.dom.DocumentImpl,
        // destParent.getOwnerDocument() returns null.
        // #document ; com.sun.org.apache.xerces.internal.dom.DocumentImpl

        //               System.out.println(sourceNode.getNodeValue());

        //System.out.println(destParent.getNodeName() + " ; " + destParent.getClass().getName() );
        if (destParent.getOwnerDocument() == null && destParent.getNodeName().equals("#document")) {
            Node textNode = ((Document) destParent).createTextNode(sourceNode.getNodeValue());
            destParent.appendChild(textNode);
        } else {
            Node textNode = destParent.getOwnerDocument().createTextNode(sourceNode.getNodeValue());
            // Warning: If you attempt to write a single "&" character, it will be converted to &amp; 
            // even if it doesn't look like that with getNodeValue() or getTextContent()!
            // So avoid any tricks with entities! See notes in docx2xhtmlNG2.xslt
            Node appended = destParent.appendChild(textNode);

        }
        break;

    //                case Node.CDATA_SECTION_NODE:
    //                    writer.write("<![CDATA[" +
    //                                 node.getNodeValue() + "]]>");
    //                    break;
    //
    //                case Node.COMMENT_NODE:
    //                    writer.write(indentLevel + "<!-- " +
    //                                 node.getNodeValue() + " -->");
    //                    writer.write(lineSeparator);
    //                    break;
    //
    //                case Node.PROCESSING_INSTRUCTION_NODE:
    //                    writer.write("<?" + node.getNodeName() +
    //                                 " " + node.getNodeValue() +
    //                                 "?>");
    //                    writer.write(lineSeparator);
    //                    break;
    //
    //                case Node.ENTITY_REFERENCE_NODE:
    //                    writer.write("&" + node.getNodeName() + ";");
    //                    break;
    //
    //                case Node.DOCUMENT_TYPE_NODE:
    //                    DocumentType docType = (DocumentType)node;
    //                    writer.write("<!DOCTYPE " + docType.getName());
    //                    if (docType.getPublicId() != null)  {
    //                        System.out.print(" PUBLIC \"" +
    //                            docType.getPublicId() + "\" ");
    //                    } else {
    //                        writer.write(" SYSTEM ");
    //                    }
    //                    writer.write("\"" + docType.getSystemId() + "\">");
    //                    writer.write(lineSeparator);
    //                    break;
    }
}

From source file:org.eclipse.swordfish.p2.internal.deploy.server.MetadataProcessor.java

/**
 * Append a child node to an owner node//from w ww .  ja v a2  s . co m
 * @param parent - the parent node
 * @param childName - the name of the child node
 * @return the child node that was added
 */
private final Element appendChild(Node parent, String childName) {
    Element e = parent.getOwnerDocument().createElement(childName);
    parent.appendChild(e);
    return e;
}

From source file:org.etudes.mneme.impl.ImportQti2ServiceImpl.java

/**
 * /*from w  w w  . j a v  a  2s .co  m*/
 * @param node
 * @param textContent
 * @return
 */
private String getAllLevelsTextContent(Node node, StringBuilder textContent, boolean wholeText,
        String unzipLocation, String context, List<String> embedMedia) {
    NodeList list = node.getChildNodes();

    for (int i = 0; i < list.getLength(); ++i) {
        Node child = list.item(i);

        String childTagName = child.getNodeName();

        if (child.getNodeType() == Node.TEXT_NODE) {
            textContent.append(child.getTextContent());

        }
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            if (wholeText && ("img".equalsIgnoreCase(childTagName) || "a".equalsIgnoreCase(childTagName)
                    || "object".equalsIgnoreCase(childTagName))) {
                try {
                    processEmbedMedia((Element) child, unzipLocation, context, embedMedia);
                } catch (Exception e) {
                    // do nothing
                }
            }

            if (!wholeText && child.getNodeName().contains("Interaction")) {
                if (child.getTextContent() != null)
                    textContent.append(child.getTextContent());
            } else if (child.getNodeName().contains("feedback")) {
                // do nothing skip it
            } else if (child.getNodeName().contains("printedVariable")) {
                Element printedVariableTemplate = null;
                Element currNodeElement = (Element) child;
                String id = currNodeElement.getAttribute("identifier");
                try {
                    XPath printedPath = new DOMXPath(
                            ".//setTemplateValue[@identifier='" + id + "']//randomInteger");
                    printedVariableTemplate = (Element) printedPath.selectSingleNode(child.getOwnerDocument());
                } catch (Exception e) {
                    printedVariableTemplate = null;
                }
                if (printedVariableTemplate != null)
                    textContent.append(this.messages.getString("import_qti2_printedVariable_text")
                            + printedVariableTemplate.getAttribute("min") + " - "
                            + printedVariableTemplate.getAttribute("max") + " "
                            + this.messages.getString("import_qti2_printedVariable_text2"));
            } else {
                textContent.append("<" + child.getNodeName());

                if (child.hasAttributes()) {
                    NamedNodeMap attrs = child.getAttributes();
                    for (int k = 0; k < attrs.getLength(); k++) {
                        Node attr = attrs.item(k);
                        textContent.append(" " + attr.getNodeName() + " = \"" + attr.getTextContent() + "\" ");
                    }
                }
                textContent.append(">");

                getAllLevelsTextContent(child, textContent, wholeText, unzipLocation, context, embedMedia);

                textContent.append("</" + child.getNodeName() + ">");
            }
        }
    }
    return textContent.toString();
}

From source file:org.exist.xmldb.TestEXistXMLSerialize.java

@Test
public void serialize1()
        throws TransformerException, XMLDBException, ParserConfigurationException, SAXException, IOException {
    Collection testCollection = DatabaseManager.getCollection(ROOT_URI + "/" + TEST_COLLECTION);
    System.out.println("Xerces version: " + org.apache.xerces.impl.Version.getVersion());
    XMLResource resource = (XMLResource) testCollection.createResource(null, "XMLResource");

    Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(testFile);

    resource.setContentAsDOM(doc);/* www .  j a va 2 s  .  c  o  m*/
    System.out.println("Storing resource: " + resource.getId());
    testCollection.storeResource(resource);

    resource = (XMLResource) testCollection.getResource(resource.getId());
    assertNotNull(resource);
    Node node = resource.getContentAsDOM();
    node = node.getOwnerDocument();

    System.out.println("Attempting serialization 1");
    DOMSource source = new DOMSource(node);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(out);

    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);

    System.out.println("Using javax.xml.transform.Transformer");
    System.out.println("---------------------");
    System.out.println(new String(out.toByteArray()));
    System.out.println("--------------------- ");
}

From source file:org.firesoa.common.jxpath.model.dom.W3CDomFactory.java

private void addW3CDomElement(Node parent, int index, String tag, String namespaceURI) {
    try {/*  ww  w .jav a2 s.c  om*/
        Node child = parent.getFirstChild();
        int count = 0;
        while (child != null) {
            if (child.getNodeName().equals(tag)) {
                count++;
            }
            child = child.getNextSibling();
        }

        // Keep inserting new elements until we have index + 1 of them
        while (count <= index) {
            Document doc = parent.getOwnerDocument();
            Node newElement;
            if (namespaceURI == null) {
                newElement = doc.createElement(tag);
            } else {
                newElement = doc.createElementNS(namespaceURI, tag);
            }

            parent.appendChild(newElement);
            count++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.infoscoop.service.SiteAggregationMenuService.java

public synchronized void addMenuItem(String id, String parentId, String title, String href, String display,
        String type, Map props, String alert, String menuType, Collection auths, Boolean linkDisabled,
        String directoryTitle, String sitetopId, boolean multi) throws Exception {

    href = StringUtil.getTruncatedString(href, 1024, "UTF-8");

    if (log.isInfoEnabled()) {
        log.info("AddMenuItem: title=" + title + ", href=" + href + ", display=" + display + ", type=" + type
                + ", alert" + alert + ", properties=" + props);
    }/*  ww  w. j a  va 2s.  c o  m*/
    // Obtain data and transfer the result to Document.
    Siteaggregationmenu_temp entity = this.siteAggregationMenuTempDAO.selectBySitetopId(menuType, sitetopId);

    Node node = getTargetElement(entity, parentId);

    // Error
    if (node == null)
        throw new Exception("element not found [//site],[//site-top]");

    Document document = node.getOwnerDocument();

    Element element;
    element = document.createElement("site");
    element.setAttribute("id", id);
    element.setAttribute("title", title);
    element.setAttribute("href", href);
    element.setAttribute("display", display);
    element.setAttribute("link_disabled", linkDisabled.toString());
    element.setAttribute("multi", String.valueOf(multi));
    element.setAttribute("type", type);
    if (alert != null && !"".equals(alert))
        element.setAttribute("alert", alert);
    if (directoryTitle != null && !"".equals(directoryTitle))
        element.setAttribute("directory_title", directoryTitle);

    element.appendChild(recreatePropertiesNode(document, element, props));

    if (auths != null) {
        element.appendChild(MenuAuthorization.createAuthsElement(document, auths));
    }

    // Added at last
    node.appendChild(element);

    // Update
    entity.setElement(document.getDocumentElement());
    this.siteAggregationMenuTempDAO.update(entity);
}

From source file:org.infoscoop.service.SiteAggregationMenuService.java

public synchronized void updateMenuItem(String menuId, String title, String href, String display, String type,
        String serviceURL, String serviceAuthType, Map props, String alert, String menuType, Collection auths,
        Collection<String> menuTreeAdmins, Boolean linkDisabled, String directoryTitle, String sitetopId,
        boolean multi) throws Exception {

    href = StringUtil.getTruncatedString(href, 1024, "UTF-8");

    if (log.isInfoEnabled()) {
        log.info("UpdateMenuItem: menuId=" + menuId + ", title=" + title + ", " + title + ", href=" + href
                + ", display=" + display + ", alert" + alert + ", properties=" + props);
    }//from   w  w  w.j  a  v a2 s  . c  om
    // Obtain data and transfer the result to Document.
    Siteaggregationmenu_temp entity = this.siteAggregationMenuTempDAO.selectBySitetopId(menuType, sitetopId);
    Node node = getTargetElement(entity, menuId);

    // Error
    if (node == null)
        throw new Exception("element not found [//site],[//site-top]");

    Document document = node.getOwnerDocument();

    // Create element to be updated
    Element element;
    element = (Element) node;
    element.setAttribute("title", title);
    element.setAttribute("href", href);
    element.setAttribute("display", display);
    element.setAttribute("link_disabled", linkDisabled.toString());
    if (serviceURL != null)
        element.setAttribute("serviceURL", serviceURL);
    if (serviceAuthType != null)
        element.setAttribute("serviceAuthType", serviceAuthType);
    if (alert != null && !"".equals(alert))
        element.setAttribute("alert", alert);

    element.setAttribute("multi", String.valueOf(multi));

    element.setAttribute("type", type);

    if (directoryTitle != null && !"".equals(directoryTitle)) {
        element.setAttribute("directory_title", directoryTitle);
    } else if (element.hasAttribute("directory_title")) {
        element.removeAttribute("directory_title");
    }

    element.insertBefore(recreatePropertiesNode(document, element, props), element.getFirstChild());

    Element oldAuths = getFirstChildElementByName(element, "auths");
    if (oldAuths != null) {
        element.removeChild(oldAuths);
    }
    if (auths != null) {
        element.insertBefore(MenuAuthorization.createAuthsElement(document, auths),
                getFirstChildElementByName(element, "site"));
    }

    NodeList oldAdmins = element.getElementsByTagName("menuTreeAdmins");
    if (oldAdmins != null) {
        while (oldAdmins.getLength() != 0) {
            oldAdmins.item(0).getParentNode().removeChild(oldAdmins.item(0));
        }
    }
    if (menuTreeAdmins != null) {
        element.insertBefore(createAdminsElement(document, menuTreeAdmins),
                getFirstChildElementByName(element, "site"));
    }

    // Update
    entity.setElement(document.getDocumentElement());
    this.siteAggregationMenuTempDAO.update(entity);
}

From source file:org.infoscoop.service.SiteAggregationMenuService.java

public synchronized String removeMenuItem(String menuType, String menuId, String sitetopId) throws Exception {

    if (log.isInfoEnabled()) {
        log.info("RemoveMenuItem: menuId=" + menuId);
    }/*from   w  w  w . java2 s.c om*/
    // Obtain data and transfer the result to Document.
    Siteaggregationmenu_temp entity = this.siteAggregationMenuTempDAO.selectBySitetopId(menuType, sitetopId);
    Node node = getTargetElement(entity, menuId, true);

    // Error
    if (node == null)
        throw new Exception("element not found [//site],[//site-top]");

    Document document = node.getOwnerDocument();

    Set<String> removeMenuIdSet = new HashSet<String>();
    removeMenuIdSet.add(menuId);
    NodeList removeMenuItems = ((Element) node).getElementsByTagName("site");
    for (int i = 0; i < removeMenuItems.getLength(); i++) {
        Element menuItem = (Element) removeMenuItems.item(i);
        removeMenuIdSet.add(menuItem.getAttribute("id"));
    }

    // Delete node matches menuId
    AdminServiceUtil.removeSelf(node);

    // Update
    entity.setElement(document.getDocumentElement());
    this.siteAggregationMenuTempDAO.update(entity);

    JSONArray response = new JSONArray();
    for (String mid : removeMenuIdSet) {
        response.put(mid);
    }
    return response.toString();
}

From source file:org.jboss.tools.aerogear.hybrid.core.plugin.CordovaPluginManager.java

private List<IPluginInstallationAction> getHeaderFileActionsForPlatform(Node node,
        AbstractPluginInstallationActionsFactory factory) {
    ArrayList<IPluginInstallationAction> list = new ArrayList<IPluginInstallationAction>();
    NodeList headerFiles = CordovaPluginXMLHelper.getHeaderFileNodes(node);
    for (int i = 0; i < headerFiles.getLength(); i++) {
        Node current = headerFiles.item(i);
        String src = getAttributeValue(current, "src");
        String targetDir = getAttributeValue(current, "target-dir");
        String id = CordovaPluginXMLHelper.getAttributeValue(node.getOwnerDocument().getDocumentElement(),
                "id");
        IPluginInstallationAction action = factory.getHeaderFileAction(src, targetDir, id);
        list.add(action);/* w  ww  .ja  v a 2s.  co  m*/
    }
    return list;
}