001 /* 002 @license.text@ 003 */ 004 005 package biz.hammurapi.xml.dom; 006 007 import javax.xml.xpath.XPathExpressionException; 008 009 import org.w3c.dom.Document; 010 import org.w3c.dom.Element; 011 import org.w3c.dom.Node; 012 import org.w3c.dom.NodeList; 013 import org.w3c.dom.Text; 014 015 import biz.hammurapi.xml.dom.DOMUtils; 016 017 /** 018 * @author Pavel Vlasov 019 * @version $Revision: 1.4 $ 020 */ 021 public class AbstractDomObject { 022 023 public static String getElementText(Element root, String child) throws XPathExpressionException { 024 Node n=DOMUtils.selectSingleNode(root, child); 025 return n==null ? null : getElementText(n); 026 } 027 028 /** 029 * @param node 030 * @return Concatenation of all text sub 031 */ 032 public static String getElementText(Node node) { 033 StringBuffer ret=new StringBuffer(); 034 NodeList childNodes = node.getChildNodes(); 035 for (int i=0, j=childNodes.getLength(); i<j; i++) { 036 Node item = childNodes.item(i); 037 if (item instanceof Text) { 038 ret.append(item.getNodeValue()); 039 } 040 } 041 return ret.toString(); 042 } 043 044 /** 045 * Adds element with text if text is not null. 046 * @param root 047 * @param name 048 * @param text 049 */ 050 public static Element addTextElement(Element root, String name, String text) { 051 if (text!=null) { 052 Element e=addElement(root, name); 053 e.appendChild(root.getOwnerDocument().createTextNode(text)); 054 return e; 055 } 056 return null; 057 } 058 059 /** 060 * Adds element with specified name. 061 * @param root 062 * @param name 063 * @return 064 */ 065 public static Element addElement(Node root, String name) { 066 Document doc = root instanceof Document ? (Document) root : root.getOwnerDocument(); 067 Element ret=doc.createElement(name); 068 root.appendChild(ret); 069 return ret; 070 } 071 }