Java XML: Obtenir le texte d’un enfant dans un document DOM

Author:

Java XML: Obtenir le texte d'un enfant dans un document DOM
{filelink=8558}

/***** Code de MesExemples.com *******/
/**
 * @(#)XMLChildText.java
 *
 *
 * @author 
 *sakoba(java.mesexemples.com) @version 1.00 2013/7/5
 */

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLChildText {

  public static String getChildText(Element parent, String childName) {
    NodeList list_node = parent.getElementsByTagName(childName);
    if (list_node.getLength() > 1) {
      throw new IllegalStateException("Multiple child elements with name " + 
    childName);
    } else if (list_node.getLength() == 0) {
      return null;
    }
    Element child = (Element) list_node.item(0);
    return getText(child);
  }

  public static String getText(Element element) {
    StringBuffer buf = new StringBuffer();
    NodeList list_node = element.getChildNodes();
    boolean found = false;
    for (int i = 0; i < list_node.getLength(); i++) {
      Node node = list_node.item(i);
      if (node.getNodeType() == Node.TEXT_NODE) {
        buf.append(node.getNodeValue());
        found = true;
      }
    }
    return found ? buf.toString() : null;
  }
}

Code testé avec le fichier XML Suivant




	Sakoba
	Adams
	Rappel
	Ne m'oubliez pas ce week-end!

A Voir sur le même Sujet:

  • exemple code java

Leave a Reply

Your email address will not be published. Required fields are marked *