Java Code Examples for org.w3c.dom.Node#getNextSibling()

The following examples show how to use org.w3c.dom.Node#getNextSibling() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DOMUtil.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/** Finds and returns the first child element node. */
public static Element getFirstChildElement(Node parent) {

    // search for node
    Node child = parent.getFirstChild();
    while (child != null) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            return (Element)child;
        }
        child = child.getNextSibling();
    }

    // not found
    return null;

}
 
Example 2
Source File: DOMUtil.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/** Finds and returns the first visible child element node. */
public static Element getFirstVisibleChildElement(Node parent, Map<Node, String> hiddenNodes) {

    // search for node
    Node child = parent.getFirstChild();
    while (child != null) {
        if (child.getNodeType() == Node.ELEMENT_NODE &&
                !isHidden(child, hiddenNodes)) {
            return (Element)child;
        }
        child = child.getNextSibling();
    }

    // not found
    return null;

}
 
Example 3
Source File: DOMUtil.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the concatenated child text of the specified node.
 * This method only looks at the immediate children of type
 * <code>Node.TEXT_NODE</code> or the children of any child
 * node that is of type <code>Node.CDATA_SECTION_NODE</code>
 * for the concatenation.
 *
 * @param node The node to look at.
 */
public static String getChildText(Node node) {

    // is there anything to do?
    if (node == null) {
        return null;
    }

    // concatenate children text
    StringBuffer str = new StringBuffer();
    Node child = node.getFirstChild();
    while (child != null) {
        short type = child.getNodeType();
        if (type == Node.TEXT_NODE) {
            str.append(child.getNodeValue());
        }
        else if (type == Node.CDATA_SECTION_NODE) {
            str.append(getChildText(child));
        }
        child = child.getNextSibling();
    }

    // return text value
    return str.toString();

}
 
Example 4
Source File: XMLUtil.java    From stendhal with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get all the direct children elements of an element.
 *
 * @param parent
 *            The parent element.
 *
 * @return A list of Element's.
 */
public static List<Element> getElements(final Element parent) {
	final LinkedList<Element> list = new LinkedList<Element>();

	Node node = parent.getFirstChild();

	while (node != null) {
		if (node.getNodeType() == Node.ELEMENT_NODE) {
			list.add((Element) node);
		}

		node = node.getNextSibling();
	}

	return list;
}
 
Example 5
Source File: RangeImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Utility method to retrieve a child node by index.  This method
 * assumes the caller is trying to find out which node is
 * selected by the given index.  Note that if the index is
 * greater than the number of children, this implies that the
 * first node selected is the parent node itself.
 *
 * @param container A container node
 *
 * @param offset    An offset within the container for which a selected node should
 *                  be computed.  If the offset is less than zero, or if the offset
 *                  is greater than the number of children, the container is returned.
 *
 * @return Returns either a child node of the container or the
 *         container itself.
 */
private Node getSelectedNode( Node container, int offset )
{
    if ( container.getNodeType() == Node.TEXT_NODE )
        return container;

    // This case is an important convenience for
    // traverseRightBoundary()
    if ( offset<0 )
        return container;

    Node child = container.getFirstChild();
    while( child!=null && offset > 0 )
    {
        --offset;
        child = child.getNextSibling();
    }
    if ( child!=null )
        return child;
    return container;
}
 
Example 6
Source File: DOMUtil.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Finds and returns the first child node with the given name and
 * attribute name, value pair.
 */
public static Element getFirstChildElement(Node   parent,
        String elemName,
        String attrName,
        String attrValue) {

    // search for node
    Node child = parent.getFirstChild();
    while (child != null) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element)child;
            if (element.getNodeName().equals(elemName) &&
                    element.getAttribute(attrName).equals(attrValue)) {
                return element;
            }
        }
        child = child.getNextSibling();
    }

    // not found
    return null;

}
 
Example 7
Source File: GenericTreeWalker.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Internal function. Return the nextSibling Node, from the input node after
 * applying filter, whatToshow. The current node is not consulted or set.
 */
private Node getNextSibling(Node node) {

	if (node == null || node == root)
		return null;

	Node newNode = node.getNextSibling();
	if (newNode == null) {
		newNode = node.getParentNode();
		if (newNode == null || node == root)
			return null;
		int parentAccept = acceptNode(newNode);
		if (parentAccept == NodeFilter.FILTER_SKIP) {
			return getNextSibling(newNode);
		}
		return null;
	}

	int accept = acceptNode(newNode);

	if (accept == NodeFilter.FILTER_ACCEPT)
		return newNode;
	else if (accept == NodeFilter.FILTER_SKIP) {
		Node fChild = getFirstChild(newNode);
		if (fChild == null)
			return getNextSibling(newNode);

		return fChild;
	} else
		// if (accept == NodeFilter.REJECT_NODE)
		return getNextSibling(newNode);

}
 
Example 8
Source File: ParentNode.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
void getTextContent(StringBuffer buf) throws DOMException {
    Node child = getFirstChild();
    while (child != null) {
        if (hasTextContent(child)) {
            ((NodeImpl) child).getTextContent(buf);
        }
        child = child.getNextSibling();
    }
}
 
Example 9
Source File: KeyInfo.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Searches the per-KeyInfo KeyResolvers for secret keys
 *
 * @return the secret key contained in this KeyInfo
 * @throws KeyResolverException
 */

SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException {
    for (KeyResolverSpi keyResolver : internalKeyResolvers) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
        }
        keyResolver.setSecureValidation(secureValidation);
        Node currentChild = this.constructionElement.getFirstChild();
        String uri = this.getBaseURI();
        while (currentChild != null)      {
            if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
                for (StorageResolver storage : storageResolvers) {
                    SecretKey sk =
                        keyResolver.engineLookupAndResolveSecretKey(
                            (Element) currentChild, uri, storage
                        );

                    if (sk != null) {
                        return sk;
                    }
                }
            }
            currentChild = currentChild.getNextSibling();
        }
    }

    return null;
}
 
Example 10
Source File: XMLUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param sibling
 * @param uri
 * @param nodeName
 * @param number
 * @return nodes with the constrain
 */
public static Element selectNode(Node sibling, String uri, String nodeName, int number) {
    while (sibling != null) {
        if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri)
            && sibling.getLocalName().equals(nodeName)) {
            if (number == 0){
                return (Element)sibling;
            }
            number--;
        }
        sibling = sibling.getNextSibling();
    }
    return null;
}
 
Example 11
Source File: XLSXmlParser.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private void readXml() throws FHIRException  {
  Element root = xml.getDocumentElement();
  check(root.getNamespaceURI().equals(XLS_NS), "Spreadsheet namespace incorrect");
  check(root.getNodeName().equals("Workbook"), "Spreadsheet element name incorrect");
  Node node = root.getFirstChild();
  while (node != null) {
    if (node.getNodeName().equals("Worksheet"))
      processWorksheet((Element)node);
    node = node.getNextSibling();
  }
}
 
Example 12
Source File: KeyInfo.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Searches the per-KeyInfo KeyResolvers for public keys
 *
 * @return The public key contained in this Node.
 * @throws KeyResolverException
 */
PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException {
    for (KeyResolverSpi keyResolver : internalKeyResolvers) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
        }
        keyResolver.setSecureValidation(secureValidation);
        Node currentChild = this.constructionElement.getFirstChild();
        String uri = this.getBaseURI();
        while (currentChild != null)      {
            if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
                for (StorageResolver storage : storageResolvers) {
                    PublicKey pk =
                        keyResolver.engineLookupAndResolvePublicKey(
                            (Element) currentChild, uri, storage
                        );

                    if (pk != null) {
                        return pk;
                    }
                }
            }
            currentChild = currentChild.getNextSibling();
        }
    }

    return null;
}
 
Example 13
Source File: IIOMetadataNode.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void getElementsByTagName(String name, List l) {
    if (nodeName.equals(name)) {
        l.add(this);
    }

    Node child = getFirstChild();
    while (child != null) {
        ((IIOMetadataNode)child).getElementsByTagName(name, l);
        child = child.getNextSibling();
    }
}
 
Example 14
Source File: mxObjectCodec.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Decodec all children of the given node using decodeChild.
 */
protected void decodeChildren(mxCodec dec, Node node, Object obj) {
  Node child = node.getFirstChild();

  while (child != null) {
    if (child.getNodeType() == Node.ELEMENT_NODE && !processInclude(dec, child, obj)) {
      decodeChild(dec, child, obj);
    }

    child = child.getNextSibling();
  }
}
 
Example 15
Source File: IIOMetadataNode.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public Node item(int index) {
    if (index < 0) {
        return null;
    }

    Node child = getFirstChild();
    while (child != null && index-- > 0) {
        child = child.getNextSibling();
    }
    return child;
}
 
Example 16
Source File: mxChildChangeCodec.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Reads the cells into the graph model. All cells are children of the root
 * element in the node.
 */
public Node beforeDecode(mxCodec dec, Node node, Object into) {
  if (into instanceof mxChildChange) {
    mxChildChange change = (mxChildChange)into;

    if (node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
      // Makes sure the original node isn't modified
      node = node.cloneNode(true);

      Node tmp = node.getFirstChild();
      change.setChild(dec.decodeCell(tmp, false));

      Node tmp2 = tmp.getNextSibling();
      tmp.getParentNode().removeChild(tmp);
      tmp = tmp2;

      while (tmp != null) {
        tmp2 = tmp.getNextSibling();

        if (tmp.getNodeType() == Node.ELEMENT_NODE) {
          // Ignores all existing cells because those do not need
          // to be re-inserted into the model. Since the encoded
          // version of these cells contains the new parent, this
          // would leave to an inconsistent state on the model
          // (ie. a parent change without a call to
          // parentForCellChanged).
          String id = ((Element)tmp).getAttribute("id");

          if (dec.lookup(id) == null) {
            dec.decodeCell(tmp, true);
          }
        }

        tmp.getParentNode().removeChild(tmp);
        tmp = tmp2;
      }
    }
    else {
      String childRef = ((Element)node).getAttribute("child");
      change.setChild((mxICell)dec.getObject(childRef));
    }
  }

  return node;
}
 
Example 17
Source File: RangeImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public void insertNode(Node newNode)
    throws DOMException, RangeException
{
    if ( newNode == null ) return; //throw exception?

    int type = newNode.getNodeType();

    if (fDocument.errorChecking) {
        if (fDetach) {
            throw new DOMException(
                    DOMException.INVALID_STATE_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null));
        }
        if ( fDocument != newNode.getOwnerDocument() ) {
            throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null));
        }

        if (type == Node.ATTRIBUTE_NODE
                || type == Node.ENTITY_NODE
                || type == Node.NOTATION_NODE
                || type == Node.DOCUMENT_NODE)
        {
            throw new RangeExceptionImpl(
                    RangeException.INVALID_NODE_TYPE_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_NODE_TYPE_ERR", null));
        }
    }
    Node cloneCurrent;
    Node current;
    int currentChildren = 0;
    fInsertedFromRange = true;

    //boolean MULTIPLE_MODE = false;
    if (fStartContainer.getNodeType() == Node.TEXT_NODE) {

        Node parent = fStartContainer.getParentNode();
        currentChildren = parent.getChildNodes().getLength(); //holds number of kids before insertion
        // split text node: results is 3 nodes..
        cloneCurrent = fStartContainer.cloneNode(false);
        ((TextImpl)cloneCurrent).setNodeValueInternal(
                (cloneCurrent.getNodeValue()).substring(fStartOffset));
        ((TextImpl)fStartContainer).setNodeValueInternal(
                (fStartContainer.getNodeValue()).substring(0,fStartOffset));
        Node next = fStartContainer.getNextSibling();
        if (next != null) {
                if (parent !=  null) {
                    parent.insertBefore(newNode, next);
                    parent.insertBefore(cloneCurrent, next);
                }
        } else {
                if (parent != null) {
                    parent.appendChild(newNode);
                    parent.appendChild(cloneCurrent);
                }
        }
         //update ranges after the insertion
         if ( fEndContainer == fStartContainer) {
              fEndContainer = cloneCurrent; //endContainer is the new Node created
              fEndOffset -= fStartOffset;
         }
         else if ( fEndContainer == parent ) {    //endContainer was not a text Node.
              //endOffset + = number_of_children_added
               fEndOffset += (parent.getChildNodes().getLength() - currentChildren);
         }

         // signal other Ranges to update their start/end containers/offsets
         signalSplitData(fStartContainer, cloneCurrent, fStartOffset);


    } else { // ! TEXT_NODE
        if ( fEndContainer == fStartContainer )      //need to remember number of kids
            currentChildren= fEndContainer.getChildNodes().getLength();

        current = fStartContainer.getFirstChild();
        int i = 0;
        for(i = 0; i < fStartOffset && current != null; i++) {
            current=current.getNextSibling();
        }
        if (current != null) {
            fStartContainer.insertBefore(newNode, current);
        } else {
            fStartContainer.appendChild(newNode);
        }
        //update fEndOffset. ex:<body><p/></body>. Range(start;end): body,0; body,1
        // insert <h1>: <body></h1><p/></body>. Range(start;end): body,0; body,2
        if ( fEndContainer == fStartContainer && fEndOffset != 0 ) {     //update fEndOffset if not 0
            fEndOffset += (fEndContainer.getChildNodes().getLength() - currentChildren);
        }
    }
    fInsertedFromRange = false;
}
 
Example 18
Source File: Nodes.java    From caja with Apache License 2.0 4 votes vote down vote up
void renderSibs(Node sib, Namespaces ns, boolean renderUnsafe) {
  for (; sib != null; sib = sib.getNextSibling()) {
    render(sib, ns, renderUnsafe);
  }
}
 
Example 19
Source File: DocumentBase.java    From L2jBrasil with GNU General Public License v3.0 4 votes vote down vote up
protected Lambda getLambda(Node n, Object template)
{
    Node nval = n.getAttributes().getNamedItem("val");
    if (nval != null)
    {
        String val = nval.getNodeValue();
        if (val.charAt(0) == '#')
        { // table by level
            return new LambdaConst(Double.parseDouble(getTableValue(val)));
        }
        else if (val.charAt(0) == '$')
        {
            if (val.equalsIgnoreCase("$player_level"))
                return new LambdaStats(LambdaStats.StatsType.PLAYER_LEVEL);
            if (val.equalsIgnoreCase("$target_level"))
                return new LambdaStats(LambdaStats.StatsType.TARGET_LEVEL);
            if (val.equalsIgnoreCase("$player_max_hp"))
                return new LambdaStats(LambdaStats.StatsType.PLAYER_MAX_HP);
            if (val.equalsIgnoreCase("$player_max_mp"))
                return new LambdaStats(LambdaStats.StatsType.PLAYER_MAX_MP);
            // try to find value out of item fields
            StatsSet set = getStatsSet();
            String field = set.getString(val.substring(1));
            if (field != null)
            {
            	return new LambdaConst(Double.parseDouble(getValue(field, template)));
            }
            // failed
            throw new IllegalArgumentException("Unknown value " + val);
        }
        else
        {
            return new LambdaConst(Double.parseDouble(val));
        }
    }
    LambdaCalc calc = new LambdaCalc();
    n = n.getFirstChild();
    while (n != null && n.getNodeType() != Node.ELEMENT_NODE)
        n = n.getNextSibling();
    if (n == null || !"val".equals(n.getNodeName()))
        throw new IllegalArgumentException("Value not specified");

    for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
    {
        if (n.getNodeType() != Node.ELEMENT_NODE) continue;
        attachLambdaFunc(n, template, calc);
    }
    return calc;
}
 
Example 20
Source File: RangeImpl.java    From openjdk-8-source with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Visits the nodes selected by this range when we know
 * a-priori that the start and end containers are not
 * the same, and we also know that neither the start
 * nor end container is an ancestor of the other.
 * This method is invoked by
 * the generic <code>traverse</code> method.
 *
 * @param startAncestor
 *               Given a common ancestor of the start and end containers,
 *               this parameter is the ancestor (or self) of the start
 *               container that is a direct child of the common ancestor.
 *
 * @param endAncestor
 *               Given a common ancestor of the start and end containers,
 *               this parameter is the ancestor (or self) of the end
 *               container that is a direct child of the common ancestor.
 *
 * @param how    Specifies what type of traversal is being
 *               requested (extract, clone, or delete).
 *               Legal values for this argument are:
 *
 *               <ol>
 *               <li><code>EXTRACT_CONTENTS</code> - will produce
 *               a document fragment containing the range's content.
 *               Partially selected nodes are copied, but fully
 *               selected nodes are moved.
 *
 *               <li><code>CLONE_CONTENTS</code> - will leave the
 *               context tree of the range undisturbed, but sill
 *               produced cloned content in a document fragment
 *
 *               <li><code>DELETE_CONTENTS</code> - will delete from
 *               the context tree of the range, all fully selected
 *               nodes.
 *               </ol>
 *
 * @return Returns a document fragment containing any
 *         copied or extracted nodes.  If the <code>how</code>
 *         parameter was <code>DELETE_CONTENTS</code>, the
 *         return value is null.
 */
private DocumentFragment
    traverseCommonAncestors( Node startAncestor, Node endAncestor, int how )
{
    DocumentFragment frag = null;
    if ( how!=DELETE_CONTENTS)
        frag = fDocument.createDocumentFragment();

    Node n = traverseLeftBoundary( startAncestor, how );
    if ( frag!=null )
        frag.appendChild( n );

    Node commonParent = startAncestor.getParentNode();
    int startOffset = indexOf( startAncestor, commonParent );
    int endOffset = indexOf( endAncestor, commonParent );
    ++startOffset;

    int cnt = endOffset - startOffset;
    Node sibling = startAncestor.getNextSibling();

    while( cnt > 0 )
    {
        Node nextSibling = sibling.getNextSibling();
        n = traverseFullySelected( sibling, how );
        if ( frag!=null )
            frag.appendChild( n );
        sibling = nextSibling;
        --cnt;
    }

    n = traverseRightBoundary( endAncestor, how );
    if ( frag!=null )
        frag.appendChild( n );

    if ( how != CLONE_CONTENTS )
    {
        setStartAfter( startAncestor );
        collapse( true );
    }
    return frag;
}