Here you can find the source of getElementText(Element elem, boolean mandatory)
Parameter | Description |
---|---|
elem | The root element to look for children in. |
mandatory | true when an exception should be thrown if the text does not exist. |
Parameter | Description |
---|---|
Exception | When text is required and not found. |
public static String getElementText(Element elem, boolean mandatory) throws Exception
//package com.java2s; /* (c) 2014 Open Source Geospatial Foundation - all rights reserved * (c) 2001 - 2013 OpenPlans/*from w w w .j av a 2 s. c om*/ * This code is licensed under the GPL 2.0 license, available at the root * application directory. */ import java.util.logging.Level; import java.util.logging.Logger; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** Used internally to create log information to detect errors. */ private static final Logger LOGGER = Logger .getLogger("org.vfny.geoserver.global"); /** * getChildText purpose. * * <p> * Used to help with XML manipulations. Returns the text value of the * specified element name. * </p> * * @param elem The root element to look for children in. * * @return The value if the text was found, the null otherwise. */ public static String getElementText(Element elem) { try { return getElementText(elem, false); } catch (Exception ex) { return null; } } /** * getChildText purpose. * * <p> * Used to help with XML manipulations. Returns the text value of the * specified element name. An exception occurs when the node is required * and not found. * </p> * * @param elem The root element to look for children in. * @param mandatory true when an exception should be thrown if the text * does not exist. * * @return The value if the text was found, the null otherwise. * * @throws Exception When text is required and not found. */ public static String getElementText(Element elem, boolean mandatory) throws Exception { String value = null; if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer(new StringBuffer("getting element text for ") .append(elem).toString()); } if (elem != null) { Node child; NodeList childs = elem.getChildNodes(); int nChilds = childs.getLength(); for (int i = 0; i < nChilds; i++) { child = childs.item(i); if (child.getNodeType() == Node.TEXT_NODE) { value = child.getNodeValue(); if (mandatory && "".equals(value.trim())) { throw new Exception(elem.getNodeName() + " text is empty"); } break; } } if (mandatory && (value == null)) { throw new Exception(elem.getNodeName() + " element does not contains text"); } } else { throw new Exception("Argument element can't be null"); } return value; } }