Java tutorial
//package com.java2s; import org.w3c.dom.*; public class Main { /** Helper method - gets a named element's value as a <I>Byte</I>. @param pElement The parent <I>Element</I>. @param strName Name of the element. @return Value of the element. */ public static byte getElementByte(Element pElement, String strName) throws ClassCastException, NumberFormatException { int nReturn = getElementInt(pElement, strName); if (Integer.MIN_VALUE == nReturn) return Byte.MIN_VALUE; return (byte) nReturn; } /** Helper method - gets a named element's value as an <I>int</I>. @param pElement The parent <I>Element</I>. @param strName Name of the element. @return Value of the element. */ public static int getElementInt(Element pElement, String strName) throws ClassCastException, NumberFormatException { String strValue = getElementString(pElement, strName); if (null == strValue) return Integer.MIN_VALUE; return Integer.parseInt(strValue); } /** Helper method - gets a named element's value as a <I>String</I>. @param pElement The parent <I>Element</I>. @param strName Name of the element. @return Value of the element. */ public static String getElementString(Element pElement, String strName) throws ClassCastException { Node pNodeValue = findNode(pElement, strName); if (null == pNodeValue) return null; return getNodeText(pNodeValue); } /** Helper method - finds the node with the specified element name. The returned node can be the passed in node itself or one of its child nodes. The first node found is the one returned. @param pNode A <I>org.w3c.dom.Node</I> object being searched. @param strElementName Name of the element being searched for. @return <I>org.w3c.dom.Node</I> object. */ public static Node findNode(Node pNode, String strElementName) { // Check the parent, first. if (pNode.getNodeName().equals(strElementName)) return pNode; NodeList pNodeList = null; if (pNode instanceof Element) pNodeList = ((Element) pNode).getElementsByTagName(strElementName); else if (pNode instanceof Document) pNodeList = ((Document) pNode).getElementsByTagName(strElementName); if ((null == pNodeList) || (0 == pNodeList.getLength())) return null; return pNodeList.item(0); } /** Helper method - gets the text value of an element node. The text value is stored in the child nodes. @param pNode A org.w3c.dom.Node object. @return Element's text. */ public static String getNodeText(Node pNode) { NodeList pChildren = pNode.getChildNodes(); int nLength = pChildren.getLength(); if (0 == nLength) return null; String strReturn = ""; for (int i = 0; i < nLength; i++) { Node pChild = pChildren.item(i); if (pChild instanceof CharacterData) strReturn += ((CharacterData) pChild).getData(); } if (0 == strReturn.length()) return null; return strReturn; } }