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:org.dhatim.xml.DomUtils.java

/**
 * Count the DOM element nodes before the supplied node, having the specified 
 * tag name, not including the node itself.
 * <p/>//from  ww w  .  java2s.com
 * Counts the sibling nodes.
 * @param node Node whose element siblings are to be counted.
 * @param tagName The tag name of the sibling elements to be counted. 
 * @return The number of siblings elements before the supplied node with the 
 * specified tag name.
 */
public static int countElementsBefore(Node node, String tagName) {
    AssertArgument.isNotNull(node, "node");
    AssertArgument.isNotNullAndNotEmpty(tagName, "tagName");

    Node parent = node.getParentNode();
    if (parent == null) {
        logger.debug("Cannot count nodes before [" + node + "]. [" + node + "] has no parent.");
        return 0;
    }

    NodeList siblings = parent.getChildNodes();
    int count = 0;
    int siblingCount = siblings.getLength();

    for (int i = 0; i < siblingCount; i++) {
        Node sibling = siblings.item(i);

        if (sibling == node) {
            break;
        }
        if (sibling.getNodeType() == Node.ELEMENT_NODE && ((Element) sibling).getTagName().equals(tagName)) {
            count++;
        }
    }

    return count;
}

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

/**
 * Get all the text DOM sibling nodes before the supplied node and 
 * concatenate them together into a single String.
 * @param node Text node./*from  w  ww  .j a va 2 s.c  o  m*/
 * @return String containing the concatentated text.
 */
public static String getTextBefore(Node node) {
    AssertArgument.isNotNull(node, "node");

    Node parent = node.getParentNode();
    if (parent == null) {
        logger.debug("Cannot get text before node [" + node + "]. [" + node + "] has no parent.");
        return "";
    }

    NodeList siblings = parent.getChildNodes();
    StringBuffer text = new StringBuffer();
    int siblingCount = siblings.getLength();

    for (int i = 0; i < siblingCount; i++) {
        Node sibling = siblings.item(i);

        if (sibling == node) {
            break;
        }
        if (sibling.getNodeType() == Node.TEXT_NODE) {
            text.append(((Text) sibling).getData());
        }
    }

    return text.toString();
}

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

/**
 * Get all the text DOM sibling nodes before the supplied node and 
 * concatenate them together into a single String.
 * @param node1 Test node.//from  w  w  w .  j a  va  2 s  .  c  o m
 * @return String containing the concatentated text.
 */
public static String getTextBetween(Node node1, Node node2) {
    AssertArgument.isNotNull(node1, "node1");
    AssertArgument.isNotNull(node2, "node2");

    Node parent1 = node1.getParentNode();
    if (parent1 == null) {
        logger.debug("Cannot get text between nodes [" + node1 + "] and [" + node2 + "]. [" + node1
                + "] has no parent.");
        return "";
    }

    Node parent2 = node2.getParentNode();
    if (parent2 == null) {
        logger.debug("Cannot get text between nodes [" + node1 + "] and [" + node2 + "]. [" + node2
                + "] has no parent.");
        return "";
    }

    if (parent1 != parent2) {
        logger.debug("Cannot get text between nodes [" + node1 + "] and [" + node2
                + "]. These nodes do not share the same sparent.");
        return "";
    }

    NodeList siblings = parent1.getChildNodes();
    StringBuffer text = new StringBuffer();
    boolean append = false;
    int siblingCount = siblings.getLength();

    for (int i = 0; i < siblingCount; i++) {
        Node sibling = siblings.item(i);

        if (sibling == node1) {
            append = true;
        }
        if (sibling == node2) {
            break;
        }
        if (append && sibling.getNodeType() == Node.TEXT_NODE) {
            text.append(((Text) sibling).getData());
        }
    }

    return text.toString();
}

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

/**
 * Construct the XPath of the supplied DOM Node.
 * <p/>// w ww .ja  v  a 2s. co  m
 * Supports element, comment and cdata sections DOM Node types.
 * @param node DOM node for XPath generation.
 * @return XPath string representation of the supplied DOM Node.
 */
public static String getXPath(Node node) {
    AssertArgument.isNotNull(node, "node");

    StringBuffer xpath = new StringBuffer();
    Node parent = node.getParentNode();

    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        xpath.append(getXPathToken((Element) node));
        break;
    case Node.COMMENT_NODE:
        int commentNum = DomUtils.countNodesBefore(node, Node.COMMENT_NODE);
        xpath.append("/{COMMENT}[" + commentNum + 1 + "]");
        break;
    case Node.CDATA_SECTION_NODE:
        int cdataNum = DomUtils.countNodesBefore(node, Node.CDATA_SECTION_NODE);
        xpath.append("/{CDATA}[" + cdataNum + 1 + "]");
        break;
    default:
        throw new UnsupportedOperationException(
                "XPath generation for supplied DOM Node type not supported.  Only supports element, comment and cdata section DOM nodes.");
    }

    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE) {
        xpath.insert(0, getXPathToken((Element) parent));
        parent = parent.getParentNode();
    }

    return xpath.toString();
}

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

private void normalizeSpace(final Node node) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        for (final Node n : getChildren(node)) {
            normalizeSpace(n);/*  w  ww.j a va  2s  .com*/
        }
        break;
    case Node.TEXT_NODE:
        final String v = node.getNodeValue().replaceAll("\\s+", " ").trim();
        if (v.isEmpty()) {
            node.getParentNode().removeChild(node);
        } else {
            node.setNodeValue(v);
        }
        break;
    }
}

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

private void addStubElements() {
    stub = rootTopicref.getOwnerDocument().createElement(ELEMENT_STUB);
    siblingStub = rootTopicref.getOwnerDocument().createElement(ELEMENT_STUB);
    if (rootTopicref.hasChildNodes()) {
        final NodeList list = rootTopicref.getElementsByTagName(MAP_TOPICMETA.localName);
        if (list.getLength() > 0) {
            final Node node = list.item(0);
            final Node nextSibling = node.getNextSibling();
            // no sibling so node is the last child
            if (nextSibling == null) {
                node.getParentNode().appendChild(stub);
            } else {
                // has sibling node
                node.getParentNode().insertBefore(stub, nextSibling);
            }/*from   ww  w . ja  va 2  s  .  c  o m*/
        } else {
            // no topicmeta tag.
            rootTopicref.insertBefore(stub, rootTopicref.getFirstChild());
        }
    } else {
        rootTopicref.appendChild(stub);
    }
}

From source file:org.dspace.content.authority.DSpaceControlledVocabulary.java

private String buildString(Node node) {
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        return ("");
    } else {/*  w w  w .ja  v  a2s .com*/
        String parentValue = buildString(node.getParentNode());
        Node currentLabel = node.getAttributes().getNamedItem("label");
        if (currentLabel != null) {
            String currentValue = currentLabel.getNodeValue();
            if (parentValue.equals("")) {
                return currentValue;
            } else {
                return (parentValue + this.hierarchyDelimiter + currentValue);
            }
        } else {
            return (parentValue);
        }
    }
}

From source file:org.easyrec.service.core.impl.ProfileServiceImpl.java

/**
 * Used//from w w  w. j a va  2  s .c  om
 * @param tenantId
 * @param itemId
 * @param itemType
 * @param deleteXPath
 * @throws Exception
 *
 */
@Override
public boolean deleteProfileField(Integer tenantId, String itemId, String itemType, String deleteXPath)
        throws Exception {

    XPathFactory xpf = XPathFactory.newInstance();

    // load and parse the profile
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemType))));

    // check if the element exists
    XPath xp = xpf.newXPath();
    NodeList nodeList = (NodeList) xp.evaluate(deleteXPath, doc, XPathConstants.NODESET);

    if (nodeList.getLength() == 0)
        throw new FieldNotFoundException("Field does not exist in this profile!");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }

    StringWriter writer = new StringWriter();
    Result result = new StreamResult(writer);
    trans.transform(new DOMSource(doc), result);
    writer.close();
    String xml = writer.toString();
    logger.debug(xml);
    storeProfile(tenantId, itemId, itemType, xml);

    return true;
}

From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java

public void insertOrUpdateMultiDimension(Integer tenantId, Integer itemId, String itemTypeId,
        String dimensionXPath, List<String> values) {

    XPathFactory xpf = XPathFactory.newInstance();

    try {/*w  w w.  j  a  v  a  2s  .c  om*/
        // load and parse the profile
        DocumentBuilder db = validationParsers.get(tenantId).get(itemTypeId);
        Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemTypeId))));
        // check if the element exists
        Node node = null;
        Node parent = null;
        XPath xp = xpf.newXPath();
        for (Iterator<String> it = values.iterator(); it.hasNext();) {
            String value = it.next();
            // look if value already exists
            node = (Node) xp.evaluate(dimensionXPath + "[text()='" + value + "']", doc, XPathConstants.NODE);
            // if value exists, value can be discarded
            if (node != null) {
                // optimization: if a node was found, store the parent; later no new XPath evaluation is necessary
                parent = node.getParentNode();
                it.remove();
            }
        }
        if (values.isEmpty())
            return; // nothing left to do
        String parentPath = dimensionXPath.substring(0, dimensionXPath.lastIndexOf("/"));
        // find path to parent
        if (parent == null) {
            String tmpPath = parentPath;
            while (parent == null) {
                tmpPath = parentPath.substring(0, tmpPath.lastIndexOf("/"));
                parent = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE);
            }
            parent = insertElement(doc, parent, parentPath.substring(tmpPath.length()), null);
        }
        String tag = dimensionXPath.substring(parentPath.length() + 1);
        for (String value : values) {
            Element el = doc.createElement(tag);
            el.setTextContent(value);
            parent.appendChild(el);
        }

        StringWriter writer = new StringWriter();
        Result result = new StreamResult(writer);
        trans.transform(new DOMSource(doc), result);
        writer.close();
        String xml = writer.toString();
        logger.debug(xml);
        storeProfile(tenantId, itemId, itemTypeId, xml, true);

    } catch (Exception e) {
        logger.error("Error inserting Multi Dimension: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.eclipse.birt.report.engine.emitter.docx.writer.BasicComponent.java

/**
 * test if the text node is in the script
 * /*w  w  w. j  a  v a  2  s  . co m*/
 * @param node
 *            text node
 * @return true if the text is a script, otherwise, false.
 */
private boolean isScriptText(Node node) {
    Node parent = node.getParentNode();
    if (parent != null) {
        if (parent.getNodeType() == Node.ELEMENT_NODE) {
            String tag = parent.getNodeName();
            if (HTMLTags.TAG_SCRIPT.equalsIgnoreCase(tag)) {
                return true;
            }
        }
    }
    return false;
}