1
2
3
4
5
6
7 package org.astrogrid.datacenter;
8
9 import java.util.Vector;
10 import org.w3c.dom.Element;
11 import org.w3c.dom.Node;
12 import org.w3c.dom.NodeList;
13
14 /***
15 * Dom Helper methods that have yet to get moved to common
16 * <p>
17 * @author M Hill
18 */
19
20 public class DsaDomHelper
21 {
22
23 /*** Sets the value of the element ot the given string *and removes all
24 * element children* - see
25 * getValue() of DomHelper
26 */
27 public static void setElementValue(Element element, String value) {
28
29 NodeList children = element.getChildNodes();
30 for (int c = 0; c < children.getLength(); c++) {
31 if (children.item(c).getNodeType() == Node.TEXT_NODE ) {
32 children.item(c).setNodeValue(value);
33 return;
34 }
35 }
36
37 element.appendChild(element.getOwnerDocument().createTextNode(value));
38
39 }
40
41 /*** Returns the first child element of the given name of the given parent
42 * element. If there is more than one, throws an exception. If there is
43 * none, returns null
44 @todo move to DomHelper */
45 public static Element getSingleChildByTagName(Element parent, String tagName) {
46 Element[] children = getChildrenByTagName(parent, tagName);
47 if (children == null) {
48 return null;
49 }
50 else if (children.length>1) {
51
52 throw new IllegalArgumentException("More than one "+tagName+" element in "+parent.getNodeName());
53 }
54 else if (children.length>0) {
55 return children[0];
56 }
57 else {
58 return null;
59 }
60 }
61
62 /*** a bit like getChildrenByTagName but returns only those elements that are
63 * direct children of the given parent
64 @todo move to DomHelper
65 */
66 public static Element[] getChildrenByTagName(Element parent, String name) {
67 if (parent == null) {
68 return null;
69 }
70 Vector v = new Vector();
71 NodeList c = parent.getChildNodes();
72 for (int n = 0; n < c.getLength(); n++) {
73 if (c.item(n) instanceof Element) {
74
75 if ( ((Element) c.item(n)).getLocalName().equals(name)) {
76 v.add( c.item(n));
77 }
78 }
79 }
80 return (Element[]) v.toArray(new Element[] {});
81 }
82
83 /*** Returns the child with the given name - creating it if it doesn't exist */
84 public static Element ensuredGetSingleChild(Element parent, String childName) {
85 Element tag = DsaDomHelper.getSingleChildByTagName(parent, childName);
86 if (tag == null) {
87 tag = parent.getOwnerDocument().createElementNS(parent.getNamespaceURI(), childName);
88 parent.appendChild(tag);
89 }
90 return tag;
91 }
92
93
94 }
95
96