1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package com.openholdem.util;
24
25 import org.w3c.dom.NodeList;
26 import org.w3c.dom.Node;
27 import org.w3c.dom.Element;
28 import org.w3c.dom.Text;
29
30
31
32 /***
33 **
34 ** <p>This class was taken from an O'Reilly site on DOM utilities. It contains a few helper methods
35 ** to make extracting out XML text from DOM representations a little easier.
36 ** </p>
37 **
38 ** @author Chris Mattmann
39 ** @version $Revision: 1.2 $
40 **
41 **/
42 public class DOMUtil{
43
44 /***
45 ** <p>Method returns the First occurence of Element 'name' in the DOM Node 'element'.
46 ** </p>
47 **
48 ** @param element The DOM Element node to traverse.
49 ** @param name The XML name of the Element to return.
50 **
51 ** @return Element "element" with Name "name"'s first occurence.
52 **
53 **/
54 public static Element getFirstElement(Element element,String name) throws Exception
55 {
56 NodeList n1 = element.getElementsByTagName(name);
57
58 if(n1.getLength() < 1){
59 throw new Exception("Element: "+element+" does not contain: "+name);
60 }
61
62 return (Element)n1.item(0);
63 }
64
65 /***
66 ** <p>This function is intended when you have a DOM element with no other DOM elements inside (i.e. <Tag><Tag2>here is text</Tag2></Tag>)
67 ** </p>
68 **
69 ** @param node The DOM 'SimpleElement' as defined in the Function definition.
70 ** @param name The name of the Text to retreive.
71 **
72 ** @return the Text inbetween the simple element tags.
73 **
74 **/
75 public static String getSimpleElementText(Element node,String name) throws Exception{
76 Element namedElement = getFirstElement(node,name);
77 return getSimpleElementText(namedElement);
78 }
79
80
81 /***
82 ** <p>This function is intended for use when you have merely text between an XML Element (i.e. <Tag>text here</Tag>).</p>
83 **
84 ** @param node The DOM XML Tag, with text inbetween.
85 ** @return String text inbetween the simple element tag.
86 **
87 **/
88 public static String getSimpleElementText(Element node){
89 StringBuffer sb = new StringBuffer();
90 NodeList children = node.getChildNodes();
91
92 for(int i=0; i < children.getLength(); i++){
93 Node child = children.item(i);
94 if(child instanceof Text){
95 sb.append(child.getNodeValue());
96 }
97 }
98
99 return sb.toString();
100 }
101 }
102
103
104