Java: Obtenir le premier enfant direct d’un nœud avec un attribut donné

Author:

Java: Obtenir le premier enfant direct d'un nœud avec un attribut donné
Download

/***** Code de MesExemples.com *******/
import org.w3c.dom.Node;
/** *   * * @author Costin Manolache */
public class Main {
  /** Find the first direct child with a given attribute.   
  * @param parent   * @param elemName name of the element, or null for any    
  * @param attName attribute we're looking for   * @param attVal attribute value or null if we just want any  
  */
 
  public static Node findChildWithAtt(Node parent, String elemName, String attName, String attVal) {
            Node child=DomUtil.getChild(parent, Node.ELEMENT_NODE);
      if( attVal== null ) {
          while( child!= null &&( elemName==null || elemName.equals( child.getNodeName())) && DomUtil.getAttribute(child, attName) != null ) 
          {
              child=getNext(child, elemName, Node.ELEMENT_NODE );
          }      
          } else 
          {
          while( child!= null && ( elemName==null || elemName.equals( child.getNodeName())) && ! attVal.equals( DomUtil.getAttribute(child, attName)) ) 
          {
              child=getNext(child, elemName, Node.ELEMENT_NODE );
          }   
          }      return child;
          }    /**    */
   public static Node getNext( Node current, String name, int type) {
      Node first=current.getNextSibling();
      if( first==null ) return null;
      for (Node node = first;node != null;node = node.getNextSibling()) {
          if( type >= 0 && node.getNodeType() != type ) continue;
          System.out.println("getNode: " + name + " " + node.getNodeName());
          if( name==null )              
          	return node;
          if( name.equals( node.getNodeName() ) ) 
          {
              return node;
          }      
          }      
          return null;
  }
 
  }   
 

Code testé avec le fichier XML Suivant

<?xml version="1.0" encoding="windows-1252"?>
<!-- Edited by MesEXemple.com -->
<note>
	<to>Sakoba</to>
	<from>Adams</from>
	<heading>Rappel</heading>
	<body>Ne m'oubliez pas ce week-end!</body>
</note>

Cet article Java: Obtenir le premier enfant direct d’un nœud avec un attribut donné est apparu en premier sur .