JavaRanch Home    
 
This page:         last edited 16 September 2007         What's Changed?         Edit

Get Element Value By Name Using Dom   

Retrieves ElementValue? for a given XML file. Here's a method that does just that:


   /**
    * Returns the elementvalue for the given input param elementName
    * 
    * @param elementName The name of the element of which value you want
    */
   public static String getElementValue(String elementName) {
      DocumentBuilderFactory dbf = null;
      DocumentBuilder db = null;
      Document doc = null;
      try {
         dbf = DocumentBuilderFactory.newInstance();
         db = dbf.newDocumentBuilder();
         doc = db.parse("foo.xml"); // replace foo.xml with your xml file
         NodeList nodelist = doc.getElementsByTagName(elementName);
         if (null != nodelist) {
            Element elem = (Element)nodelist.item(0);
            if (null != elem) {
               Node namechild = elem.getFirstChild();
               if (null != namechild)
                  return namechild.getNodeValue();
            }
         }
      } catch (Exception e) {
         // error handling omitted
      }
      return "Not Found";
   }



XmlFaq CategoryCodeSamples

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton