1
2
3
4
5
6
7
8
9
10
11 package org.mule.util;
12
13 import org.w3c.dom.Attr;
14 import org.w3c.dom.Element;
15 import org.w3c.dom.Node;
16 import org.w3c.dom.NodeList;
17
18
19
20
21
22 public class XMLUtils
23 {
24
25 public static String elementToString(Element e)
26 {
27 StringBuffer buf = new StringBuffer();
28 buf.append(e.getTagName()).append("{");
29 for (int i = 0; i < e.getAttributes().getLength(); i++)
30 {
31 if (i > 0)
32 {
33 buf.append(", ");
34 }
35 Node n = e.getAttributes().item(i);
36 buf.append(attributeName((Attr) n)).append("=").append(n.getNodeValue());
37 }
38 buf.append("}");
39 return buf.toString();
40 }
41
42 public static boolean isLocalName(Element element, String name)
43 {
44 return element.getLocalName().equals(name);
45 }
46
47 public static String attributeName(Attr attribute)
48 {
49 String name = attribute.getLocalName();
50 if (null == name)
51 {
52 name = attribute.getName();
53 }
54 return name;
55 }
56
57 public static String getTextChild(Element element)
58 {
59 NodeList children = element.getChildNodes();
60 String value = null;
61 for (int i = 0; i < children.getLength(); ++i)
62 {
63 Node child = children.item(i);
64 if (child.getNodeType() == Node.TEXT_NODE)
65 {
66 if (null != value)
67 {
68 throw new IllegalStateException(
69 "Element " + elementToString(element) + " has more than one text child.");
70 }
71 else
72 {
73 value = child.getNodeValue();
74 }
75 }
76 }
77 return value;
78 }
79
80 }