View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.util;
8   
9   import org.w3c.dom.Attr;
10  import org.w3c.dom.Element;
11  import org.w3c.dom.Node;
12  import org.w3c.dom.NodeList;
13  
14  /**
15   * These only depend on standard (JSE) XML classes and are used by Spring config code.
16   * For a more extensive (sub-)class, see the XMLUtils class in the XML module.
17   */
18  public class XMLUtils
19  {
20  
21      public static String elementToString(Element e)
22      {
23          StringBuffer buf = new StringBuffer();
24          buf.append(e.getTagName()).append("{");
25          for (int i = 0; i < e.getAttributes().getLength(); i++)
26          {
27              if (i > 0)
28              {
29                  buf.append(", ");
30              }
31              Node n = e.getAttributes().item(i);
32              buf.append(attributeName((Attr) n)).append("=").append(n.getNodeValue());
33          }
34          buf.append("}");
35          return buf.toString();
36      }
37  
38      public static boolean isLocalName(Element element, String name)
39      {
40          return element.getLocalName().equals(name);
41      }
42  
43      public static String attributeName(Attr attribute)
44      {
45          String name = attribute.getLocalName();
46          if (null == name)
47          {
48              name = attribute.getName();
49          }
50          return name;
51      }
52  
53      public static String getTextChild(Element element)
54      {
55          NodeList children = element.getChildNodes();
56          String value = null;
57          for (int i = 0; i < children.getLength(); ++i)
58          {
59              Node child = children.item(i);
60              if (child.getNodeType() == Node.TEXT_NODE)
61              {
62                  if (null != value)
63                  {
64                      throw new IllegalStateException(
65                              "Element " + elementToString(element) + " has more than one text child.");
66                  }
67                  else
68                  {
69                      value = child.getNodeValue();
70                  }
71              }
72          }
73          return value;
74      }
75  
76  }