1 16 17 package org.springframework.util.xml; 18 19 import java.util.ArrayList ; 20 import java.util.List ; 21 22 import org.w3c.dom.CharacterData ; 23 import org.w3c.dom.Comment ; 24 import org.w3c.dom.Element ; 25 import org.w3c.dom.EntityReference ; 26 import org.w3c.dom.Node ; 27 import org.w3c.dom.NodeList ; 28 29 import org.springframework.util.Assert; 30 31 42 public abstract class DomUtils { 43 44 55 public static List getChildElementsByTagName(Element ele, String childEleName) { 56 NodeList nl = ele.getChildNodes(); 57 List childEles = new ArrayList (); 58 for (int i = 0; i < nl.getLength(); i++) { 59 Node node = nl.item(i); 60 if (node instanceof Element && nodeNameEquals(node, childEleName)) { 61 childEles.add(node); 62 } 63 } 64 return childEles; 65 } 66 67 75 public static Element getChildElementByTagName(Element ele, String childEleName) { 76 NodeList nl = ele.getChildNodes(); 77 for (int i = 0; i < nl.getLength(); i++) { 78 Node node = nl.item(i); 79 if (node instanceof Element && nodeNameEquals(node, childEleName)) { 80 return (Element ) node; 81 } 82 } 83 return null; 84 } 85 86 94 public static String getChildElementValueByTagName(Element ele, String childEleName) { 95 Element child = getChildElementByTagName(ele, childEleName); 96 return (child != null ? getTextValue(child) : null); 97 } 98 99 104 public static boolean nodeNameEquals(Node node, String desiredName) { 105 Assert.notNull(node, "Node must not be null"); 106 Assert.notNull(desiredName, "Desired name must not be null"); 107 return desiredName.equals(node.getNodeName()) || desiredName.equals(node.getLocalName()); 108 } 109 110 118 public static String getTextValue(Element valueEle) { 119 StringBuffer value = new StringBuffer (); 120 NodeList nl = valueEle.getChildNodes(); 121 for (int i = 0; i < nl.getLength(); i++) { 122 Node item = nl.item(i); 123 if ((item instanceof CharacterData && !(item instanceof Comment )) || 124 item instanceof EntityReference ) { 125 value.append(item.getNodeValue()); 126 } 127 } 128 return value.toString(); 129 } 130 131 } 132 | Popular Tags |