Java examples for XML:XML Element Child
get Child Float Value from XML Element by node name
import java.util.ArrayList; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main{ public static float getChildFloatValue(Element parent, String nodeName) throws XMLHelperException { return getNodeFloatValue(getUniqueNode(parent, nodeName)); }//from w w w . j a v a 2s . c o m public static float getNodeFloatValue(Node node) throws XMLHelperException { return (float) getNodeDoubleValue(node); } public static Node getUniqueNode(Element parent, String nodeName) throws XMLHelperException { NodeList childNodes = parent.getChildNodes(); int length = childNodes.getLength(); Node node = null; for (int i = 0; i < length; i++) { Node current = childNodes.item(i); if (current.getNodeName().equals(nodeName)) { if (node != null) throw new XMLHelperException("\"" + nodeName + "\" in \"" + parent.getNodeName() + "\" must be unique"); node = current; } } if (node == null) throw new XMLHelperException("\"" + nodeName + "\" not found in \"" + parent.getNodeName() + "\""); return node; } public static double getNodeDoubleValue(Node node) throws XMLHelperException { try { return Double.parseDouble(getNodeValue(node)); } catch (NumberFormatException e) { throw new XMLHelperException("value of \"" + node.getNodeName() + "\" must be a floating point"); } } public static String getNodeValue(Node node) throws XMLHelperException { NodeList childNodes = node.getChildNodes(); if (childNodes.getLength() > 1) throw new XMLHelperException( "can't read value - multiple child nodes"); Node textNode = childNodes.item(0); if (textNode.getNodeType() != Node.TEXT_NODE) throw new XMLHelperException( "can't read value - child node must be a text node"); return textNode.getNodeValue().trim(); } }