View Javadoc

1   /*
2    * $Id: XMLUtils.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
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   * These only depend on standard (JSE) XML classes and are used by Spring config code.
20   * For a more extensive (sub-)class, see the XMLUtils class in the XML module.
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  }