Example usage for org.w3c.dom Node getParentNode

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

Introduction

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

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:com.cloudseal.spring.client.namespace.Utility.java

public static void removeNode(final Element rootElement, final String xPathLocation)
        throws XPathExpressionException {
    final XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setNamespaceContext(new CloudSealNamespaceContext());
    final Node node = (Node) xPath.evaluate(xPathLocation, rootElement, XPathConstants.NODE);
    final short nodeType = node.getNodeType();

    switch (nodeType) {
    case Node.ELEMENT_NODE:
        final Node parent = node.getParentNode();
        parent.removeChild(node);/* w w w  . ja v a 2  s  .  com*/
        break;

    case Node.ATTRIBUTE_NODE:
        final Attr attribute = (Attr) node;
        final Element element = attribute.getOwnerElement();
        element.removeAttributeNode(attribute);
        break;

    default:
        throw new IllegalArgumentException("Not supported node type: " + nodeType);
    }
}

From source file:Main.java

static public void setElementText(Element elm, String text) {
    Node node = elm.getFirstChild();
    if (node == null) {
        if (text != null)
            elm.appendChild(elm.getOwnerDocument().createTextNode(text));
    } else if (node.getNodeType() == Node.TEXT_NODE) {
        if (text == null)
            node.getParentNode().removeChild(node);
        else/*from ww w.  j  ava 2 s .c o  m*/
            node.setNodeValue(text);
    } else if (text != null) {
        Text textNode = node.getOwnerDocument().createTextNode(text);
        elm.insertBefore(textNode, elm.getFirstChild());
    }
}

From source file:apiconnector.TestDataFunctionality.java

public static String toPrettyString(String xml, int indent) throws Exception {
    // Turn xml string into a document
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

    // Remove whitespaces outside tags
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
            XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }/*from   ww w  .ja v a2s .  com*/

    // Setup pretty print options
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute("indent-number", indent);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // Return pretty print xml string
    StringWriter stringWriter = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
    return stringWriter.toString();
}

From source file:Main.java

/**
 * Method getStrFromNode/* w w w  . j  ava 2s . c om*/
 *
 * @param xpathnode
 * @return the string for the node.
 */
public static String getStrFromNode(Node xpathnode) {
    if (xpathnode.getNodeType() == Node.TEXT_NODE) {
        // we iterate over all siblings of the context node because eventually,
        // the text is "polluted" with pi's or comments
        StringBuilder sb = new StringBuilder();

        for (Node currentSibling = xpathnode.getParentNode()
                .getFirstChild(); currentSibling != null; currentSibling = currentSibling.getNextSibling()) {
            if (currentSibling.getNodeType() == Node.TEXT_NODE) {
                sb.append(((Text) currentSibling).getData());
            }
        }

        return sb.toString();
    } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
        return xpathnode.getNodeValue();
    } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        return xpathnode.getNodeValue();
    }

    return null;
}

From source file:Main.java

/**
 * Returns parent attribute value for a specific element (2 levels of
 * parents)// ww  w  .  j  a v a2 s.c o m
 * @param element
 * @param attr
 * @return
 */
protected static String getXsdParentsAtrValue(Element element, String attr) {
    Node tmpElement = null;
    String tmpRes = "";
    try {
        for (int i = 1; i < 3; i++) {
            if (i == 1) {
                tmpElement = element.getParentNode();
            } else {
                tmpElement = tmpElement.getParentNode();
            }
            if (tmpElement.getNodeName().equals("xs:schema")) {
                if (i == 1) {
                    tmpRes = "..";
                } else {
                    tmpRes = "." + tmpRes;
                }
                break;
            }
            while ((tmpElement.getNodeType() != Node.ELEMENT_NODE)
                    || ((tmpElement.getNodeType() != Node.DOCUMENT_NODE)
                            && !((Element) tmpElement).hasAttribute(attr))) {
                if (tmpElement.getNodeName().equals("xs:schema")) {
                    break;
                }
                tmpElement = tmpElement.getParentNode();
            }
            tmpRes = ((Element) tmpElement).getAttribute(attr) + "." + tmpRes;
        }
        return tmpRes;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:hoot.services.utils.XmlDocumentBuilder.java

/**
 * Walks the document and removes all nodes of the specified type and specified name. 
 * If name is null, then the node is removed if the type matches.
 *
 * @param node starting node/*from  w w  w.  j  a v  a2 s .c  o  m*/
 * @param nodeType type of nodes to remove
 * @param name name of nodes to remove
 */
public static void removeAll(Node node, final short nodeType, final String name) {
    if (node.getNodeType() == nodeType && (name == null || node.getNodeName().equals(name))) {
        node.getParentNode().removeChild(node);
    } else {
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            removeAll(list.item(i), nodeType, name);
        }
    }
}

From source file:Main.java

/**
 * Removes text nodes that are only containing whitespace characters
 * inside a DOM tree.// www .  ja  v a2s. com
 *
 * @param element the root node to normalize.
 */
public static void stripWhitespaceNodes(Node element) {
    Node node, child;
    for (child = element.getFirstChild(); child != null; child = node) {
        node = child.getNextSibling();
        stripWhitespaceNodes(child);
    }

    if (element.getNodeType() == Node.TEXT_NODE && element.getNodeValue().trim().length() == 0) {
        element.getParentNode().removeChild(element);
    }
}

From source file:Main.java

public static String getFullPath(Node node) {
    StringBuilder buffer = new StringBuilder();
    while (node != null) {
        buffer.insert(0, node.getNodeName());
        char separator = '/';
        if (node instanceof Attr) {
            separator = '@';
        }//from  ww  w. ja  va2  s. c om
        buffer.insert(0, separator);
        node = node.getParentNode();
    }
    return buffer.toString();
}

From source file:Main.java

/**
 * Get the previous node in a DFS preorder traversal
 *
 * @param node the current node//from  ww  w .j  a  v  a  2 s  .c om
 * @return the previous node in the preorder traversal
 */
public static Node getPrevious(Node node) {
    Node previous;

    if (node == null)
        return null;

    if ((previous = node.getPreviousSibling()) != null) {
        for (; previous.getLastChild() != null; previous = previous.getLastChild()) {
        }

        return previous;
    }

    return node.getParentNode();
}

From source file:com.photon.phresco.impl.WindowsApplicationProcessor.java

private static void deleteFeature(File sourceFolderLocation, List<ArtifactGroup> deletedFeatures)
        throws PhrescoException {
    try {/*from  w w  w. j a v  a  2 s  . co m*/
        File path = new File(sourceFolderLocation + File.separator + SOURCE_DIR + File.separator + SRC_DIR
                + File.separator + PROJECT_ROOT + File.separator + PROJECT_ROOT + CSPROJ_FILE);
        if (!path.exists() && CollectionUtils.isNotEmpty(deletedFeatures)) {
            return;
        }
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(false);
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(path);
        for (ArtifactGroup deleteFeature : deletedFeatures) {
            String feature = deleteFeature.getName();
            feature = "//Reference[@Include='" + feature + "']";
            XPath xpath = XPathFactory.newInstance().newXPath();
            javax.xml.xpath.XPathExpression expr = xpath.compile(feature);
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            for (int i = 0; i < nodes.getLength(); i++) {
                Node item = nodes.item(i).getParentNode();
                item.getParentNode().removeChild(item);
            }
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(path.toURI().getPath());
        transformer.transform(source, result);

    } catch (XPathExpressionException e) {
        throw new PhrescoException(e);
    } catch (DOMException e) {
        throw new PhrescoException(e);
    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    } catch (SAXException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    } catch (TransformerConfigurationException e) {
        throw new PhrescoException(e);
    } catch (TransformerException e) {
        throw new PhrescoException(e);
    }
}