Example usage for org.w3c.dom Node getPreviousSibling

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

Introduction

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

Prototype

public Node getPreviousSibling();

Source Link

Document

The node immediately preceding this node.

Usage

From source file:org.alfresco.web.config.WebConfigRuntime.java

/**
 * @param parent//from ww  w. j  av a 2s . c  om
 * @param child
 */
private void appendChild(Node parent, Node child) {
    parent.appendChild(child);
    Node previousNode = child.getPreviousSibling();
    if (previousNode != null && previousNode instanceof org.w3c.dom.Text) {
        previousNode.getParentNode().removeChild(previousNode);
    }
}

From source file:com.wfreitas.camelsoap.SoapClient.java

private Comment getCommentBefore(Element element) {
    Node sibling = element.getPreviousSibling();

    while (sibling != null) {
        if (sibling.getNodeType() == Node.COMMENT_NODE) {
            return (Comment) sibling;
        } else if (sibling.getNodeType() == Node.TEXT_NODE) {
            // continue...
            sibling = sibling.getPreviousSibling();
        } else {//  w ww.j a  v  a  2  s  . c  o m
            // It's an Element, CData, PI etc
            return null;
        }
    }

    return null;
}

From source file:DomPrintUtil.java

private Node getVisiblePreviousSibling(Node target, Node root) {
    if (target == root) {
        return null;
    }/*from  ww w . jav a 2  s .  c  om*/
    Node tmpN = target.getPreviousSibling();
    if (null == tmpN) {
        Node tmpP = target.getParentNode();
        if (eval(tmpP) == NodeFilter.FILTER_SKIP) {
            return getVisiblePreviousSibling(tmpP, root);
        }
        return null;
    }
    switch (eval(tmpN)) {
    case NodeFilter.FILTER_ACCEPT:
        return tmpN;
    case NodeFilter.FILTER_SKIP:
        Node tmpC = getVisibleLastChild(tmpN);
        if (null != tmpC) {
            return tmpC;
        }
        // case NodeFilter.FILTER_REJECT:
    default:
        return getVisiblePreviousSibling(tmpN, root);
    }
}

From source file:jef.tools.XMLUtils.java

/**
 * ????//from ww  w.j  a  v a  2s.c  om
 * 
 * @param node
 *            
 * @param tagName
 *            ????
 * @return ?
 */
public static Element firstPrevSibling(Node node, String tagName) {
    Node p = node.getPreviousSibling();
    while (p != null) {
        if (p.getNodeType() == Node.ELEMENT_NODE) {
            if (StringUtils.isEmpty(tagName) || p.getNodeName().equals(tagName))
                return (Element) p;
        }
        p = p.getPreviousSibling();
    }
    return null;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.ClinicalDateObscurer.java

/**
 * This method removes a child from its parent (how horrible) and any preceding newlines and whitespace
 *
 * @param parent the Node holdind the child to be removed
 * @param child the Node to be removed//from  w  ww .  j ava  2s  . c  o  m
 */
private void removeChildNode(final Node parent, final Node child) {

    Node childPreviousSibling = child.getPreviousSibling();

    if (childPreviousSibling != null && childPreviousSibling.getNodeType() == Node.TEXT_NODE
            && childPreviousSibling.getTextContent().trim().equals("")) {

        //We want to remove newlines (and whitespace) preceding the child to be removed
        //so has to avoid blank lines in the XML after the child is removed
        parent.removeChild(childPreviousSibling);
    }

    //Remove child
    parent.removeChild(child);
}

From source file:com.gargoylesoftware.htmlunit.html.DomNode.java

/**
 * {@inheritDoc}//w  w w  . j  a  v a2s .c  o  m
 */
public short compareDocumentPosition(final Node other) {
    if (other == this) {
        return 0; // strange, no constant available?
    }

    // get ancestors of both
    final List<Node> myAncestors = getAncestors(true);
    final List<Node> otherAncestors = ((DomNode) other).getAncestors(true);

    final int max = Math.min(myAncestors.size(), otherAncestors.size());

    int i = 1;
    while (i < max && myAncestors.get(i) == otherAncestors.get(i)) {
        i++;
    }

    if (i != 1 && i == max) {
        if (myAncestors.size() == max) {
            return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
        }
        return DOCUMENT_POSITION_CONTAINS | DOCUMENT_POSITION_PRECEDING;
    }

    if (max == 1) {
        if (myAncestors.contains(other)) {
            return DOCUMENT_POSITION_CONTAINS;
        }
        if (otherAncestors.contains(this)) {
            return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
        }
        return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
    }

    // neither contains nor contained by
    final Node myAncestor = myAncestors.get(i);
    final Node otherAncestor = otherAncestors.get(i);
    Node node = myAncestor;
    while (node != otherAncestor && node != null) {
        node = node.getPreviousSibling();
    }
    if (node == null) {
        return DOCUMENT_POSITION_FOLLOWING;
    }
    return DOCUMENT_POSITION_PRECEDING;
}

From source file:com.occamlab.te.parsers.ImageParser.java

private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes)
        throws Exception {
    HashMap<Object, Object> bandMap = new HashMap<Object, Object>();

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("subimage")) {
                Element e = (Element) node;
                int x = Integer.parseInt(e.getAttribute("x"));
                int y = Integer.parseInt(e.getAttribute("y"));
                int w = Integer.parseInt(e.getAttribute("width"));
                int h = Integer.parseInt(e.getAttribute("height"));
                processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes());
            } else if (node.getLocalName().equals("checksum")) {
                CRC32 checksum = new CRC32();
                Raster raster = buffimage.getRaster();
                DataBufferByte buffer;
                if (node.getParentNode().getLocalName().equals("subimage")) {
                    WritableRaster outRaster = raster.createCompatibleWritableRaster();
                    buffimage.copyData(outRaster);
                    buffer = (DataBufferByte) outRaster.getDataBuffer();
                } else {
                    buffer = (DataBufferByte) raster.getDataBuffer();
                }//from  w  ww  .j  a va2 s .co m
                int numbanks = buffer.getNumBanks();
                for (int j = 0; j < numbanks; j++) {
                    checksum.update(buffer.getData(j));
                }
                Document doc = node.getOwnerDocument();
                node.appendChild(doc.createTextNode(Long.toString(checksum.getValue())));
            } else if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                if (sample.equals("all")) {
                    bandMap.put(band, null);
                } else {
                    HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band);
                    if (sampleMap == null) {
                        if (!bandMap.containsKey(band)) {
                            sampleMap = new HashMap<Object, Object>();
                            bandMap.put(band, sampleMap);
                        }
                    }
                    sampleMap.put(Integer.decode(sample), new Integer(0));
                }
            } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24
                                                                          // PwD
                String transparentNodata = checkTransparentNodata(buffimage, node);
                node.setTextContent(transparentNodata);
            }
        }
    }

    Iterator bandIt = bandMap.keySet().iterator();
    while (bandIt.hasNext()) {
        String band_str = (String) bandIt.next();
        int band_indexes[];
        if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY
                || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            band_indexes = new int[1];
            band_indexes[0] = 0;
        } else {
            band_indexes = new int[band_str.length()];
            for (int i = 0; i < band_str.length(); i++) {
                if (band_str.charAt(i) == 'A')
                    band_indexes[i] = 3;
                if (band_str.charAt(i) == 'B')
                    band_indexes[i] = 2;
                if (band_str.charAt(i) == 'G')
                    band_indexes[i] = 1;
                if (band_str.charAt(i) == 'R')
                    band_indexes[i] = 0;
            }
        }

        Raster raster = buffimage.getRaster();
        java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str);
        boolean addall = (sampleMap == null);
        if (sampleMap == null) {
            sampleMap = new java.util.HashMap();
            bandMap.put(band_str, sampleMap);
        }

        int minx = raster.getMinX();
        int maxx = minx + raster.getWidth();
        int miny = raster.getMinY();
        int maxy = miny + raster.getHeight();
        int bands[][] = new int[band_indexes.length][raster.getWidth()];

        for (int y = miny; y < maxy; y++) {
            for (int i = 0; i < band_indexes.length; i++) {
                raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]);
            }
            for (int x = minx; x < maxx; x++) {
                int sample = 0;
                for (int i = 0; i < band_indexes.length; i++) {
                    sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8);
                }

                Integer sampleObj = new Integer(sample);

                boolean add = addall;
                if (!addall) {
                    add = sampleMap.containsKey(sampleObj);
                }
                if (add) {
                    Integer count = (Integer) sampleMap.get(sampleObj);
                    if (count == null) {
                        count = new Integer(0);
                    }
                    count = new Integer(count.intValue() + 1);
                    sampleMap.put(sampleObj, count);
                }
            }
        }
    }

    Node node = nodes.item(0);
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                HashMap sampleMap = (HashMap) bandMap.get(band);
                Document doc = node.getOwnerDocument();
                if (sample.equals("all")) {
                    Node parent = node.getParentNode();
                    Node prevSibling = node.getPreviousSibling();
                    Iterator sampleIt = sampleMap.keySet().iterator();
                    Element countnode = null;
                    int digits;
                    String prefix;
                    switch (buffimage.getType()) {
                    case BufferedImage.TYPE_BYTE_BINARY:
                        digits = 1;
                        prefix = "";
                        break;
                    case BufferedImage.TYPE_BYTE_GRAY:
                        digits = 2;
                        prefix = "0x";
                        break;
                    default:
                        prefix = "0x";
                        digits = band.length() * 2;
                    }
                    while (sampleIt.hasNext()) {
                        countnode = doc.createElementNS(node.getNamespaceURI(), "count");
                        Integer sampleInt = (Integer) sampleIt.next();
                        Integer count = (Integer) sampleMap.get(sampleInt);
                        if (band.length() > 0) {
                            countnode.setAttribute("bands", band);
                        }
                        countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits));
                        Node textnode = doc.createTextNode(count.toString());
                        countnode.appendChild(textnode);
                        parent.insertBefore(countnode, node);
                        if (sampleIt.hasNext()) {
                            if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
                                parent.insertBefore(prevSibling.cloneNode(false), node);
                            }
                        }
                    }
                    parent.removeChild(node);
                    node = countnode;
                } else {
                    Integer count = (Integer) sampleMap.get(Integer.decode(sample));
                    if (count == null)
                        count = new Integer(0);
                    Node textnode = doc.createTextNode(count.toString());
                    node.appendChild(textnode);
                }
            }
        }
        node = node.getNextSibling();
    }
}

From source file:org.alfresco.util.XMLUtil.java

/**
 * FOR DIAGNOSTIC PURPOSES ONLY - incomplete<br/>
 * Builds a path to the node relative to the to node provided.
 * @param from the node from which to build the xpath
 * @param to an ancestor of <tt>from</tt> which will be the root of the path
 * @return an xpath to <tt>to</tt> rooted at <tt>from</tt>.
 *//*from   ww w  .ja v  a  2 s .  c o  m*/
public static String buildXPath(final Node from, final Element to) {
    String result = "";
    Node tmp = from;
    do {
        if (tmp instanceof Attr) {
            assert result.length() == 0;
            result = "@" + tmp.getNodeName();
        } else if (tmp instanceof Element) {
            Node tmp2 = tmp;
            int position = 1;
            while (tmp2.getPreviousSibling() != null) {
                if (tmp2.getNodeName().equals(tmp.getNodeName())) {
                    position++;
                }
                tmp2 = tmp2.getPreviousSibling();
            }
            String part = tmp.getNodeName() + "[" + position + "]";
            result = "/" + part + result;
        } else if (tmp instanceof Text) {
            assert result.length() == 0;
            result = "/text()";
        } else {
            if (LOGGER.isDebugEnabled()) {
                throw new IllegalArgumentException("unsupported node type " + tmp);
            }
        }
        tmp = tmp.getParentNode();
    } while (tmp != to.getParentNode() && tmp != null);
    return result;
}

From source file:org.apache.shindig.gadgets.rewrite.ConcatVisitor.java

private Node getNext(Node node, boolean isPrev) {
    return isPrev ? node.getPreviousSibling() : node.getNextSibling();
}

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

@Test
public void testWrite() throws DITAOTException, ParserConfigurationException, SAXException, IOException {
    /*/* w  w  w . java2s  . c om*/
     * the part of content of conrefpush_stub2.xml is
     * <ol>
     *    <li id="A">A</li>
     *    <li id="B">B</li>
     *    <li id="C">C</li>
     * </ol>
     * 
     * the part of content of conrefpush_stup.xml is
     *  <steps>
     *     <step conaction="pushbefore"><cmd>before</cmd></step>
     *   <step conref="conrefpush_stub2.xml#X/A" conaction="mark"/>
     *   <step conref="conrefpush_stub2.xml#X/B" conaction="mark"/>
     *    <step conaction="pushafter"><cmd>after</cmd></step>
     *    <step conref="conrefpush_stub2.xml#X/C" conaction="pushreplace"><cmd>replace</cmd></step>
     *   </steps>
     *
     * after conrefpush the part of conrefpush_stub2.xml should be like this
     * <ol class="- topic/ol ">
     *  <li class="- topic/li task/step ">
     *     <ph class="- topic/ph task/cmd ">
     *     before
     *     </ph>
     *  </li>
     *  <li id="A" class="- topic/li ">A</li>
     *   <li id="B" class="- topic/li ">B</li>
     *   <li class="- topic/li task/step ">
     *      <ph class="- topic/ph task/cmd ">
     *      after
     *      </ph>
     *   </li>
     *   <li class="- topic/li task/step ">
     *      <ph class="- topic/ph task/cmd ">
     *      replace
     *      </ph>
     *   </li>
     * </ol>
     */
    final ConrefPushParser parser = new ConrefPushParser();
    parser.setLogger(new TestUtils.TestLogger());
    parser.setJob(new Job(tempDir));
    final ConrefPushReader reader = new ConrefPushReader();

    reader.read(inputFile.getAbsoluteFile());
    final Map<File, Hashtable<MoveKey, DocumentFragment>> pushSet = reader.getPushMap();
    final Iterator<Map.Entry<File, Hashtable<MoveKey, DocumentFragment>>> iter = pushSet.entrySet().iterator();
    if (iter.hasNext()) {
        final Map.Entry<File, Hashtable<MoveKey, DocumentFragment>> entry = iter.next();
        // initialize the parsed file
        copyFile(new File(srcDir, "conrefpush_stub2_backup.xml"), entry.getKey());
        //            final Content content = new ContentImpl();
        //            content.setValue(entry.getValue());
        //            parser.setContent(content);
        parser.setMoveTable(entry.getValue());
        parser.write(entry.getKey());
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document document = builder.parse(entry.getKey());
        final Element elem = document.getDocumentElement();
        NodeList nodeList = elem.getChildNodes();
        // according to the structure, it comes to the <li> after 2 iterations.
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < nodeList.getLength(); j++) {
                if (nodeList.item(j).getNodeType() == Node.ELEMENT_NODE) {
                    nodeList = nodeList.item(j).getChildNodes();
                    break;
                }
            }
        }
        Element element;
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                element = (Element) node;
                if (element.getAttributes().getNamedItem("id") != null
                        && element.getAttributes().getNamedItem("id").getNodeValue().equals("A")) {
                    // get node of before
                    node = element.getPreviousSibling();
                    while (node.getNodeType() != Node.ELEMENT_NODE) {
                        node = node.getPreviousSibling();
                    }
                    assertEquals(
                            "<li class=\"- topic/li task/step \"><ph class=\"- topic/ph task/cmd \">before</ph></li>",
                            nodeToString((Element) node));
                } else if (element.getAttributes().getNamedItem("id") != null
                        && element.getAttributes().getNamedItem("id").getNodeValue().equals("B")) {
                    // get node of after
                    node = element.getNextSibling();
                    while (node.getNodeType() != Node.ELEMENT_NODE) {
                        node = node.getNextSibling();
                    }
                    assertEquals(
                            "<li class=\"- topic/li task/step \"><ph class=\"- topic/ph task/cmd \">after</ph></li>",
                            nodeToString((Element) node));

                    // get node of replacement
                    node = node.getNextSibling();
                    while (node.getNodeType() != Node.ELEMENT_NODE) {
                        node = node.getNextSibling();
                    }
                    assertEquals(
                            "<li class=\"- topic/li task/step \" id=\"C\"><ph class=\"- topic/ph task/cmd \">replace</ph></li>",
                            nodeToString((Element) node));
                }
            }
        }

    }
}