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    /**
016     * @author Pavel Vlasov 
017     */
018    public class AbstractDomObject {
019    
020            public static String getElementText(Element root, String child) throws XPathExpressionException {
021                    Node n=DOMUtils.selectSingleNode(root, child);
022                    return n==null ? null : getElementText(n);
023            }
024    
025            /**
026             * @param node
027             * @return Concatenation of all text sub
028             */
029            public static String getElementText(Node node) {
030                    StringBuffer ret=new StringBuffer();
031                    NodeList childNodes = node.getChildNodes();
032                    for (int i=0, j=childNodes.getLength(); i<j; i++) {
033                            Node item = childNodes.item(i);
034                            if (item instanceof Text) {
035                                    ret.append(item.getNodeValue());
036                            }
037                    }
038                    return ret.toString();
039            }
040            
041            /**
042             * Adds element with text if text is not null.
043             * @param root
044             * @param name
045             * @param text
046             */
047            public static Element addTextElement(Element root, String name, String text) {
048                if (text!=null) {
049                        Element e=addElement(root, name);
050                        e.appendChild(root.getOwnerDocument().createTextNode(text));
051                        return e;
052                }
053                return null;
054            }
055            
056            /**
057             * Adds element with specified name.
058             * @param root
059             * @param name
060             * @return
061             */
062            public static Element addElement(Node root, String name) {
063                Document doc = root instanceof Document ? (Document) root : root.getOwnerDocument();
064                Element ret=doc.createElement(name);
065                root.appendChild(ret);
066                return ret;
067            }
068    }