Example usage for org.w3c.dom Element getParentNode

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

Introduction

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

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:DomUtils.java

public static int getDepth(Element element) {
    Node parent = element.getParentNode();
    int depth = 0;

    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE) {
        depth++;/* w  ww  . ja  v  a  2  s  . c  om*/
        parent = parent.getParentNode();
    }

    return depth;
}

From source file:DomUtils.java

/**
 * Remove the supplied element from its containing document.
 * <p/>/* w  w w  . j a v a2s.c om*/
 * Tries to manage scenarios where a request is made to remove the root element.
 * Cannot remove the root element in any of the following situations:
 * <ul>
 *  <li>"keepChildren" parameter is false.</li>
 *  <li>root element is empty of {@link Node#ELEMENT_NODE} nodes.</li>
 * </ul>
 * @param element Element to be removed.
 * @param keepChildren Keep child content.
 */
public static void removeElement(Element element, boolean keepChildren) {

    Node parent = element.getParentNode();
    if (parent == null) {
        System.out.println("Cannot remove element [" + element + "]. [" + element + "] has no parent.");
        return;
    }

    NodeList children = element.getChildNodes();

    if (parent instanceof Document) {
        List childElements = null;

        if (!keepChildren) {
            System.out.println("Cannot remove document root element [" + DomUtils.getName(element)
                    + "] without keeping child content.");
        } else {
            if (children != null && children.getLength() > 0) {
                childElements = DomUtils.getElements(element, "*", null);
            }

            if (childElements != null && !childElements.isEmpty()) {
                parent.removeChild(element);
                parent.appendChild((Element) childElements.get(0));
            } else {
                System.out.println(
                        "Cannot remove empty document root element [" + DomUtils.getName(element) + "].");
            }
        }
    } else {
        if (keepChildren && children != null) {
            DomUtils.insertBefore(children, element);
        }
        parent.removeChild(element);
    }
}

From source file:DomUtils.java

/**
 * Get the parent element of the supplied element having the
 * specified tag name.//from w  w w.ja va 2 s.  c  om
 * @param child Child element. 
 * @param parentLocalName Parent element local name.
 * @param namespaceURI Namespace URI of the required parent element,
 * or null if a non-namespaced get is to be performed.
 * @return The first parent element of "child" having the tagname "parentName",
 * or null if no such parent element exists.
 */
public static Element getParentElement(Element child, String parentLocalName, String namespaceURI) {

    Node parentNode = child.getParentNode();

    while (parentNode != null && parentNode.getNodeType() == Node.ELEMENT_NODE) {
        Element parentElement = (Element) parentNode;

        if (getName(parentElement).equalsIgnoreCase(parentLocalName)) {
            if (namespaceURI == null) {
                return parentElement;
            } else if (parentElement.getNamespaceURI().equals(namespaceURI)) {
                return parentElement;
            }
        }
        parentNode = parentNode.getParentNode();
    }

    return null;
}

From source file:ar.com.zauber.commons.web.transformation.sanitizing.impl.DeletingElementNodeSanitizer.java

/** @see AbstractElementNodeSanitizer#processInvalidElements(List) */
@Override//from   ww w .  ja  v  a2 s .c  o m
public final void processInvalidElements(final List<Element> invalidElements) {

    Validate.notNull(invalidElements);

    for (Element element : invalidElements) {
        if (element.getParentNode() != null) {
            element.getParentNode().removeChild(element);
        }
    }
}

From source file:com.rapidminer.gui.OperatorDocLoader.java

/**
 * //from w w w.j a  va 2s  .co  m
 * @param operatorWikiName
 * @param opDesc
 * @return The parsed <tt>Document</tt> (not finally parsed) of the selected operator.
 * @throws MalformedURLException
 * @throws ParserConfigurationException
 */
private static Document parseDocumentForOperator(String operatorWikiName, OperatorDescription opDesc)
        throws MalformedURLException, ParserConfigurationException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setIgnoringComments(true);
    builderFactory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new XHTMLEntityResolver());

    Document document = null;
    URL url = new URL(WIKI_PREFIX_FOR_OPERATORS + operatorWikiName);
    if (url != null) {
        try {
            document = documentBuilder.parse(WebServiceTools.openStreamFromURL(url));
        } catch (IOException e) {
            logger.warning("Could not open " + url.toExternalForm() + ": " + e.getMessage());
        } catch (SAXException e) {
            logger.warning("Could not parse operator documentation: " + e.getMessage());
        }

        int i = 0;

        if (document != null) {
            Element contentElement = document.getElementById("content");

            // removing content element from document
            if (contentElement != null) {
                contentElement.getParentNode().removeChild(contentElement);
            }

            // removing everything from body
            NodeList bodies = document.getElementsByTagName("body");
            for (int k = 0; k < bodies.getLength(); k++) {
                Node body = bodies.item(k);
                while (body.hasChildNodes()) {
                    body.removeChild(body.getFirstChild());
                }

                // read content element to body
                if (contentElement != null && k == 0) {
                    body.appendChild(contentElement);
                }
            }

            // removing everything from head
            NodeList heads = document.getElementsByTagName("head");
            for (int k = 0; k < heads.getLength(); k++) {
                Node head = heads.item(k);
                while (head.hasChildNodes()) {
                    head.removeChild(head.getFirstChild());
                }
            }
            // removing...<head/> from document
            if (heads != null) {
                while (i < heads.getLength()) {
                    Node head = heads.item(i);
                    head.getParentNode().removeChild(head);
                }
            }

            // removing jump-to-nav element from document
            Element jumpToNavElement = document.getElementById("jump-to-nav");
            if (jumpToNavElement != null) {
                jumpToNavElement.getParentNode().removeChild(jumpToNavElement);
            }

            // removing mw-normal-catlinks element from document
            Element mwNormalCatlinksElement = document.getElementById("mw-normal-catlinks");
            if (mwNormalCatlinksElement != null) {
                mwNormalCatlinksElement.getParentNode().removeChild(mwNormalCatlinksElement);
            }

            // removing complete link navigation
            Element tocElement = document.getElementById("toc");
            if (tocElement != null) {
                tocElement.getParentNode().removeChild(tocElement);
            }

            // removing everything from class printfooter
            NodeList nodeListDiv = document.getElementsByTagName("div");
            for (int k = 0; k < nodeListDiv.getLength(); k++) {
                Element div = (Element) nodeListDiv.item(k);
                if (div.getAttribute("class").equals("printfooter")) {
                    div.getParentNode().removeChild(div);
                }
            }

            // removing everything from class editsection
            NodeList spanList = document.getElementsByTagName("span");
            for (int k = 0; k < spanList.getLength(); k++) {
                Element span = (Element) spanList.item(k);
                if (span.getAttribute("class").equals("editsection")) {
                    span.getParentNode().removeChild(span);
                }
            }

            // Synopsis Header
            boolean doIt = true;
            NodeList pList = document.getElementsByTagName("p");
            for (int k = 0; k < pList.getLength(); k++) {

                if (doIt) {
                    Node p = pList.item(k);
                    NodeList pChildList = p.getChildNodes();

                    for (int j = 0; j < pChildList.getLength(); j++) {

                        Node pChild = pChildList.item(j);
                        if (pChild.getNodeType() == Node.TEXT_NODE && pChild.getNodeValue() != null
                                && StringUtils.isNotBlank(pChild.getNodeValue())
                                && StringUtils.isNotEmpty(pChild.getNodeValue())) {

                            String pChildString = pChild.getNodeValue();
                            Element newPWithoutSpaces = document.createElement("p");
                            newPWithoutSpaces.setTextContent(pChildString);

                            Node synopsis = document.createTextNode("Synopsis");

                            Element span = document.createElement("span");
                            span.setAttribute("class", "mw-headline");
                            span.setAttribute("id", "Synopsis");
                            span.appendChild(synopsis);

                            Element h2 = document.createElement("h2");
                            h2.appendChild(span);

                            Element div = document.createElement("div");
                            div.setAttribute("id", "synopsis");
                            div.appendChild(h2);
                            div.appendChild(newPWithoutSpaces);

                            Node pChildParentParent = pChild.getParentNode().getParentNode();
                            Node pChildParent = pChild.getParentNode();

                            pChildParentParent.replaceChild(div, pChildParent);
                            doIt = false;
                            break;
                        }
                    }
                } else {
                    break;
                }
            }

            // removing all <br...>-Tags
            NodeList brList = document.getElementsByTagName("br");

            while (i < brList.getLength()) {
                Node br = brList.item(i);
                Node parentBrNode = br.getParentNode();
                parentBrNode.removeChild(br);
            }

            // removing everything from script
            NodeList scriptList = document.getElementsByTagName("script");
            while (i < scriptList.getLength()) {
                Node scriptNode = scriptList.item(i);
                Node parentNode = scriptNode.getParentNode();
                parentNode.removeChild(scriptNode);
            }

            // removing all empty <p...>-Tags
            NodeList pList2 = document.getElementsByTagName("p");
            int ccc = 0;
            while (ccc < pList2.getLength()) {
                Node p = pList2.item(ccc);
                NodeList pChilds = p.getChildNodes();

                int kk = 0;

                while (kk < pChilds.getLength()) {
                    Node pChild = pChilds.item(kk);
                    if (pChild.getNodeType() == Node.TEXT_NODE) {
                        String pNodeValue = pChild.getNodeValue();
                        if (pNodeValue == null || StringUtils.isBlank(pNodeValue)
                                || StringUtils.isEmpty(pNodeValue)) {
                            kk++;
                        } else {
                            ccc++;
                            break;
                        }
                    } else {
                        ccc++;
                        break;
                    }
                    if (kk == pChilds.getLength()) {
                        Node parentBrNode = p.getParentNode();
                        parentBrNode.removeChild(p);
                    }
                }
            }

            // removing firstHeading element from document
            Element firstHeadingElement = document.getElementById("firstHeading");
            if (firstHeadingElement != null) {
                CURRENT_OPERATOR_NAME_READ_FROM_RAPIDWIKI = firstHeadingElement.getFirstChild().getNodeValue()
                        .replaceFirst(".*:", "");
                firstHeadingElement.getParentNode().removeChild(firstHeadingElement);
            }

            // setting operator plugin name
            if (opDesc != null && opDesc.getProvider() != null) {
                CURRENT_OPERATOR_PLUGIN_NAME = opDesc.getProvider().getName();
            }

            // removing sitesub element from document
            Element siteSubElement = document.getElementById("siteSub");
            if (siteSubElement != null) {
                siteSubElement.getParentNode().removeChild(siteSubElement);
            }

            // removing contentSub element from document
            Element contentSubElement = document.getElementById("contentSub");
            if (contentSubElement != null) {
                contentSubElement.getParentNode().removeChild(contentSubElement);
            }

            // removing catlinks element from document
            Element catlinksElement = document.getElementById("catlinks");
            if (catlinksElement != null) {
                catlinksElement.getParentNode().removeChild(catlinksElement);
            }

            // removing <a...> element from document, if they are empty
            NodeList aList = document.getElementsByTagName("a");
            if (aList != null) {
                int k = 0;
                while (k < aList.getLength()) {
                    Node a = aList.item(k);
                    Element aElement = (Element) a;
                    if (aElement.getAttribute("class").equals("internal")) {
                        a.getParentNode().removeChild(a);
                    } else {
                        Node aChild = a.getFirstChild();
                        if (aChild != null
                                && (aChild.getNodeValue() != null && aChild.getNodeType() == Node.TEXT_NODE
                                        && StringUtils.isNotBlank(aChild.getNodeValue())
                                        && StringUtils.isNotEmpty(aChild.getNodeValue())
                                        || aChild.getNodeName() != null)) {
                            Element aChildElement = null;
                            if (aChild.getNodeName().startsWith("img")) {
                                aChildElement = (Element) aChild;

                                Element imgElement = document.createElement("img");
                                imgElement.setAttribute("alt", aChildElement.getAttribute("alt"));
                                imgElement.setAttribute("class", aChildElement.getAttribute("class"));
                                imgElement.setAttribute("height", aChildElement.getAttribute("height"));
                                imgElement.setAttribute("src",
                                        WIKI_PREFIX_FOR_IMAGES + aChildElement.getAttribute("src"));
                                imgElement.setAttribute("width", aChildElement.getAttribute("width"));
                                imgElement.setAttribute("border", "1");

                                Node aParent = a.getParentNode();
                                aParent.replaceChild(imgElement, a);
                            } else {
                                k++;
                            }
                        } else {
                            a.getParentNode().removeChild(a);
                        }
                    }
                }
            }

        }
    }
    return document;
}

From source file:net.phoenix.thrift.xml.ArgBeanDefinitionParser.java

@Override
protected void preParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    Element parent = (Element) element.getParentNode();
    String argsBeanDefinitionName = parent.getAttribute("id");
    String name = element.getAttribute("name");
    builder.addPropertyReference("targetObject", argsBeanDefinitionName);
    builder.addPropertyValue("targetMethod", name);
}

From source file:net.phoenix.thrift.xml.ArgsBeanDefinitionParser.java

/**
 * socketNonblockingServerTNonblockingServerSocket
 * @param element// w  w w  . jav  a2s .  c  o  m
 * @return
 */
private Class<? extends TServerTransport> parseSocketClass(Element argsElement) {
    Element parent = (Element) argsElement.getParentNode();
    String serverClassName = parent.getAttribute("class");
    Class<?> serverClass;
    try {
        serverClass = Class.forName(serverClassName);
    } catch (ClassNotFoundException e) {
        throw new BeanCreationException("Could not found thrift server with class '" + serverClassName + "'.");
    }

    if (AbstractNonblockingServer.class.isAssignableFrom(serverClass)) {
        LOG.info("Using '" + TNonblockingServerSocket.class + "' for server transport.");
        return TNonblockingServerSocket.class;
    } else {
        LOG.info("Using '" + TServerSocket.class + "' for server transport.");
        return TServerSocket.class;
    }
}

From source file:net.phoenix.thrift.xml.ArgBeanDefinitionParser.java

/**
 * register to the bean factory;//from  w  w  w.j  a va  2 s  . co m
 *
 * @param element
 * @param parserContext
 * @param current
 */
private void registerBeanDefinition(Element element, ParserContext parserContext,
        AbstractBeanDefinition current) {
    try {
        Element parent = (Element) element.getParentNode();
        String argsBeanDefinitionName = parent.getAttribute("id");
        String name = argsBeanDefinitionName + "-" + element.getAttribute("name");
        String[] alias = null;
        if (StringUtils.hasLength(name)) {
            alias = StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray(name));
        }
        BeanDefinitionHolder holder = new BeanDefinitionHolder(current, name, alias);
        registerBeanDefinition(holder, parserContext.getRegistry());
    } catch (BeanDefinitionStoreException ex) {
        parserContext.getReaderContext().error(ex.getMessage(), element);
    }
}

From source file:WebAppConfig.java

/**
 * This method adds a new name-to-class mapping in in the form of a <servlet>
 * sub-tree to the document./*from   ww  w. ja  v  a 2  s  .  c o  m*/
 */
public void addServlet(String servletName, String className) {
    // Create the <servlet> tag
    Element newNode = document.createElement("servlet");
    // Create the <servlet-name> and <servlet-class> tags
    Element nameNode = document.createElement("servlet-name");
    Element classNode = document.createElement("servlet-class");
    // Add the name and classname text to those tags
    nameNode.appendChild(document.createTextNode(servletName));
    classNode.appendChild(document.createTextNode(className));
    // And add those tags to the servlet tag
    newNode.appendChild(nameNode);
    newNode.appendChild(classNode);

    // Now that we've created the new sub-tree, figure out where to put
    // it. This code looks for another servlet tag and inserts the new
    // one right before it. Note that this code will fail if the document
    // does not already contain at least one <servlet> tag.
    NodeList servletnodes = document.getElementsByTagName("servlet");
    Element firstServlet = (Element) servletnodes.item(0);

    // Insert the new node before the first servlet node
    firstServlet.getParentNode().insertBefore(newNode, firstServlet);
}

From source file:de.erdesignerng.model.serializer.xml10.XMLAttributeSerializer.java

@Override
public void deserialize(Model aModel, ModelItem aTableOrCustomType, Element aElement) {
    // Parse the Attributes
    NodeList theAttributes = aElement.getElementsByTagName(ATTRIBUTE);
    for (int j = 0; j < theAttributes.getLength(); j++) {
        Element theAttributeElement = (Element) theAttributes.item(j);
        boolean isCustomType = "CustomType".equalsIgnoreCase(theAttributeElement.getParentNode().getNodeName());
        boolean isTable = "Table".equalsIgnoreCase(theAttributeElement.getParentNode().getNodeName());

        Attribute theAttribute = null;

        if (isTable) {
            theAttribute = new Attribute<Table>();
            theAttribute.setOwner(aTableOrCustomType);
        } else if (isCustomType) {
            theAttribute = new Attribute<CustomType>();
            theAttribute.setOwner(aTableOrCustomType);
        }//from w  w  w . jav  a 2 s . co  m

        deserializeProperties(theAttributeElement, theAttribute);
        deserializeCommentElement(theAttributeElement, theAttribute);

        String theDatatypeName = theAttributeElement.getAttribute(DATATYPE);
        theAttribute.setDatatype((StringUtils.isEmpty(theDatatypeName) ? null
                : aModel.getAvailableDataTypes().findByName(theDatatypeName)));
        theAttribute.setDefaultValue(theAttributeElement.getAttribute(DEFAULTVALUE));
        theAttribute.setSize(Integer.parseInt(theAttributeElement.getAttribute(SIZE)));
        String theFraction = theAttributeElement.getAttribute(FRACTION);
        if (!StringUtils.isEmpty(theFraction) && !"null".equals(theFraction)) {
            theAttribute.setFraction(Integer.parseInt(theFraction));
        }
        theAttribute.setScale(Integer.parseInt(theAttributeElement.getAttribute(SCALE)));
        theAttribute.setNullable(TRUE.equals(theAttributeElement.getAttribute(NULLABLE)));
        theAttribute.setExtra(theAttributeElement.getAttribute(EXTRA));

        if (isTable) {
            ((Table) aTableOrCustomType).getAttributes().add(theAttribute);
        } else if (isCustomType) {
            ((CustomType) aTableOrCustomType).getAttributes().add(theAttribute);
        }
    }
}