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:edu.stanford.muse.slant.CustomSearchHelper.java

private static void deleteCSE(String authtoken, String cseName)
        throws IOException, ParserConfigurationException, XPathExpressionException {
    // see http://code.google.com/apis/customsearch/docs/api.html

    String url = "http://www.google.com/cse/api/default/annotations/?num=5000"; // w/o num param, returns only top 20 results
    GetMethod get = new GetMethod(url);
    get.addRequestHeader("Content-type", "text/xml");
    get.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);
    int statusCode = new HttpClient().executeMethod(get);
    if (statusCode != HttpStatus.SC_OK) {
        log.warn(/* w  ww . ja v  a  2  s .  co m*/
                "Unable to read Google CSE annotations, and therefore unable to delete existing annotations! HTTP status = "
                        + statusCode);
        return;
    }

    /* sample xml: 
    <?xml version="1.0" encoding="UTF-8" ?>
    <Annotations start="0" num="2182" total="2182">
    <Annotation about="visualizing.stanford.edu/*" score="0.000810373" timestamp="0x0004b2a4c7d271fd" href="Chp2aXN1YWxpemluZy5zdGFuZm9yZC5lZHUvKhD948m-zNSsAg">
    <Label name="_cse_testengine" />
    <AdditionalData attribute="original_url" value="http://visualizing.stanford.edu/*" />
       </Annotation>
    ...
     */

    // parse xml and get href's for the annotations for this cse.
    String responseBody = IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8");
    InputSource is = new InputSource(new StringReader(responseBody));
    XPath xpath = XPathFactory.newInstance().newXPath();
    String expression = "/Annotations/Annotation/Label[@name='_cse_" + cseName + "']";
    NodeList nodes = (NodeList) xpath.evaluate(expression, is, XPathConstants.NODESET);
    List<String> hrefs = new ArrayList<String>();
    log.info(nodes.getLength() + " existing annotation(s) for search engine " + cseName
            + ". They will be deleted.");
    for (int i = 0; i < nodes.getLength(); i++) {
        Node label = nodes.item(i);
        Node annotation = label.getParentNode();
        Node hrefNode = annotation.getAttributes().getNamedItem("href");
        String href = hrefNode.getNodeValue();
        hrefs.add(href);
    }

    // hrefs now has all the existing href's for this CSE. send a remove command with these href's.
    StringBuilder removeXML = new StringBuilder("<Batch><Remove><Annotations>");
    int batchCount = 0;
    for (Iterator<String> it = hrefs.iterator(); it.hasNext();) {
        String href = it.next();
        removeXML.append(" <Annotation href=\"" + href + "\" />");
        batchCount++;
        if (batchCount == ANNOTATION_UPLOAD_BATCH_SIZE || !it.hasNext()) {
            removeXML.append("</Annotations></Remove></Batch>");
            boolean success = pushAnnotations(authtoken, removeXML.toString());
            if (!success)
                log.warn("Failed to delete " + batchCount + " existing annotations for search engine " + cseName
                        + " xml = " + removeXML);
            else
                log.info("Successfully deleted " + batchCount + " existing annotations for search engine "
                        + cseName);
            removeXML = new StringBuilder("<Batch><Remove><Annotations>");
            batchCount = 0;
        }
    }
}

From source file:XMLConfig.java

/** Return the path of a node as it is used in XMLConfig.
 * @param n node// w w  w.  j a v a2s  . c  o m
 * @return path
 */
public static String getNodePath(Node n) {
    if (n == null) {
        return "";
    }
    String path = "";
    while (n.getParentNode() != null) {
        path = n.getNodeName() + "/" + path;
        n = n.getParentNode();
    }

    return path.substring(0, path.length() - 1);
}

From source file:bridge.toolkit.commands.S1000DConverter.java

/**
 * modify scoEntryItem in scoEntryContent, move lom from scoEntryItem
 * /*  w  w  w .  java 2 s  .  c o m*/
 * @param nodes
 * @throws Exception
 */
private static void walkingthrough(Node nodes, org.w3c.dom.Document document) throws Exception {

    changeScoEntry(nodes, document);

    int length = nodes.getChildNodes().getLength();
    for (int i = 0; i < length; i++) {
        Node node = nodes.getChildNodes().item(i);

        changeScoEntry(node, document);

        if (node.getNodeName().equals("scoEntryItem")) {
            // the lom children must linked to the parent child (scoEntry)
            int lengthlom = node.getChildNodes().getLength();
            for (int lom = 0; lom < lengthlom; lom++) {
                if (node.getChildNodes().item(lom) != null
                        && node.getChildNodes().item(lom).getNodeName().equals("lom:lom")) {
                    // clone the node..
                    Node cloneLom = node.getChildNodes().item(lom).cloneNode(true);
                    // first of all I remove it
                    Node lomnode = node.getChildNodes().item(lom);
                    Node father = lomnode.getParentNode();
                    Node grandf = father.getParentNode();
                    father.removeChild(lomnode);
                    // then I add it to the new parent..
                    grandf.insertBefore(cloneLom, father);
                }

                // for each dmRef open the DM and read the real data module
                // content to be show in the lesson
                if (node.getChildNodes().item(lom) != null
                        && node.getChildNodes().item(lom).getNodeName().equals("dmRef")) {
                    String filename = resourcepack + "\\" + gettingDmfilename(node.getChildNodes().item(lom))
                            + ".xml";
                    if (new File(filename).exists()) {
                        // if the data module is a scoContent will copy each
                        // dmref in the scoEntry
                        org.w3c.dom.Document dm41 = getDoc(new File(filename));

                        if (processXPathSingleNode("dmodule/content/scoContent", dm41) != null)
                            ;
                        {
                            NodeList dmre = processXPath("/dmodule/content/scoContent/trainingStep/dmRef",
                                    dm41);
                            Node father = node.getChildNodes().item(lom).getParentNode();
                            father.removeChild(node.getChildNodes().item(lom));
                            // remove the reference to Scocontent and
                            // replace it with the dm inside
                            for (int nodi = 0; nodi < dmre.getLength(); nodi++) {
                                Node cloneref = dmre.item(nodi).cloneNode(true);
                                document.adoptNode(cloneref);
                                father.appendChild(cloneref);
                            }

                        }
                    }

                }

            }

            // rename scoEntryItem in scoEntry
            node = changeNodename(node, document, "scoEntryContent");
        }
        walkingthrough(node, document);
    }
}

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

private static org.w3c.dom.Node nextNode(org.w3c.dom.Node node) {
    // assert(node != null);
    org.w3c.dom.Node child = node.getFirstChild();

    if (child != null) {
        return child;
    }//from  w w  w  .  j a va 2  s .c  om

    org.w3c.dom.Node sib;

    while ((sib = node.getNextSibling()) == null) {
        node = node.getParentNode();

        if (node == null) {
            // End of document
            return null;
        }
    }

    return sib;
}

From source file:DomUtils.java

/**
 * Replace one node with another node./*from w  ww  .ja v  a2 s.c o  m*/
 * @param newNode New node - added in same location as oldNode.
 * @param oldNode Old node - removed.
 */
public static void replaceNode(Node newNode, Node oldNode) {

    Node parentNode = oldNode.getParentNode();

    if (parentNode == null) {
        System.out.println("Cannot replace node [" + oldNode + "] with [" + newNode + "]. [" + oldNode
                + "] has no parent.");
    } else {
        parentNode.replaceChild(newNode, oldNode);
    }
}

From source file:DomUtils.java

/**
 * Count the DOM nodes before the supplied node, not including the node itself.
 * <p/>//from w  w w . j  av  a  2s .c o m
 * Counts the sibling nodes.
 * @param node Node whose siblings are to be counted.
 * @return The number of siblings before the supplied node.
 */
public static int countNodesBefore(Node node) {
    Node parent = node.getParentNode();
    if (parent == null) {
        System.out.println("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;
        }
        count++;
    }

    return count;
}

From source file: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   ww  w. ja  v  a 2 s. c om
 * @return String containing the concatentated text.
 */
public static String getTextBefore(Node node) {
    Node parent = node.getParentNode();
    if (parent == null) {
        System.out.println("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:DomUtils.java

/**
 * Insert the supplied node before the supplied reference node (refNode).
 * @param newNode Node to be inserted.//w  ww .j ava  2  s . c  o  m
 * @param refNode Reference node before which the supplied nodes should
 * be inserted.
 */
public static void insertBefore(Node newNode, Node refNode) {

    Node parentNode = refNode.getParentNode();

    if (parentNode == null) {
        System.out.println(
                "Cannot insert [" + newNode + "] before [" + refNode + "]. [" + refNode + "] has no parent.");
        return;
    }

    if (parentNode instanceof Document && newNode.getNodeType() == Node.ELEMENT_NODE) {
        System.out.println(
                "Request to insert an element before the Document root node.  This is not allowed.  Replacing the Document root with the new Node.");
        parentNode.removeChild(refNode);
        parentNode.appendChild(newNode);
    } else {
        parentNode.insertBefore(newNode, refNode);
    }
}

From source file:DomUtils.java

/**
 * Count the DOM nodes of the supplied type (nodeType) before the supplied
 * node, not including the node itself./*from w  w w.j av  a  2s .  c  om*/
 * <p/>
 * Counts the sibling nodes.
 * @param node Node whose siblings are to be counted.
 * @param nodeType The DOM {@link Node} type of the siblings to be counted. 
 * @return The number of siblings of the supplied type before the supplied node.
 */
public static int countNodesBefore(Node node, short nodeType) {
    Node parent = node.getParentNode();
    if (parent == null) {
        System.out.println("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() == nodeType) {
            count++;
        }
    }

    return count;
}

From source file:DomUtils.java

/**
 * Count the DOM element nodes before the supplied node, having the specified 
 * tag name, not including the node itself.
 * <p/>/*from www . j a v  a  2s  . co m*/
 * 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) {
    Node parent = node.getParentNode();
    if (parent == null) {
        System.out.println("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;
}