Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.apache.tomcat.util;
 
 
 
Few simple utils to read DOM

Author(s):
Costin Manolache
 
 public class DomUtil {
 
     // -------------------- DOM utils --------------------
 
    
Get the trimed text content of a node or null if there is no text
 
     public static String getContent(Node n ) {
         ifn==null ) return null;
         Node n1=DomUtil.getChild(n.);
 
         ifn1==null ) return null;
 
         String s1=n1.getNodeValue();
         return s1.trim();
     }

    
Get the first element child.

Parameters:
parent lookup direct childs
name name of the element. If null return the first element.
 
     public static Node getChildNode parentString name ) {
         ifparent==null ) return null;
         Node first=parent.getFirstChild();
         iffirst==null ) return null;
 
         for (Node node = firstnode != null;
              node = node.getNextSibling()) {
             ifnode.getNodeType()!=.)
                 continue;
             ifname != null &&
                 name.equalsnode.getNodeName() ) ) {
                 return node;
             }
             ifname == null ) {
                 return node;
             }
         }
         return null;
     }
 
     public static String getAttribute(Node elementString attName ) {
         NamedNodeMap attrs=element.getAttributes();
         ifattrs==null ) return null;
         Node attN=attrs.getNamedItem(attName);
         ifattN==null ) return null;
         return attN.getNodeValue();
     }
 
     public static void setAttribute(Node nodeString attNameString val) {
         NamedNodeMap attributes=node.getAttributes();
         Node attNode=node.getOwnerDocument().createAttribute(attName);
         attNode.setNodeValueval );
        attributes.setNamedItem(attNode);
    }
    
    public static void removeAttributeNode nodeString attName ) {
        NamedNodeMap attributes=node.getAttributes();
        attributes.removeNamedItem(attName);                
    }
    
    
    
Set or replace the text value
 
    public static void setText(Node nodeString val) {
        Node chld=DomUtil.getChild(node.);
        ifchld == null ) {
            Node textN=node.getOwnerDocument().createTextNode(val);
            node.appendChild(textN);
            return;
        }
        // change the value
        chld.setNodeValue(val);           
    }

    
Find the first direct child with a given attribute.

Parameters:
parent
elemName name of the element, or null for any
attName attribute we're looking for
attVal attribute value or null if we just want any
 
    public static Node findChildWithAtt(Node parentString elemName,
                                        String attNameString attVal) {
        
        Node child=DomUtil.getChild(parent.);
        ifattVal== null ) {
            whilechild!= null &&
                    ( elemName==null || elemName.equalschild.getNodeName())) && 
                    DomUtil.getAttribute(childattName) != null ) {
                child=getNext(childelemName. );
            }
        } else {
            whilechild!= null && 
                    ( elemName==null || elemName.equalschild.getNodeName())) && 
                    ! attVal.equals( DomUtil.getAttribute(childattName)) ) {
                child=getNext(childelemName. );
            }
        }
        return child;        
    }    
    

    
Get the first child's content ( ie it's included TEXT node ).
    public static String getChildContentNode parentString name ) {
        Node first=parent.getFirstChild();
        iffirst==null ) return null;
        for (Node node = firstnode != null;
             node = node.getNextSibling()) {
            //System.out.println("getNode: " + name + " " + node.getNodeName());
            ifname.equalsnode.getNodeName() ) ) {
                return getContentnode );
            }
        }
        return null;
    }

    
Get the first direct child with a given type
    public static Node getChildNode parentint type ) {
        Node n=parent.getFirstChild();
        whilen!=null && type != n.getNodeType() ) {
            n=n.getNextSibling();
        }
        ifn==null ) return null;
        return n;
    }

    
Get the next sibling with the same name and type
    public static Node getNextNode current ) {
        String name=current.getNodeName();
        int type=current.getNodeType();
        return getNextcurrentnametype);
    }

    
Return the next sibling with a given name and type
 
    public static Node getNextNode currentString nameint type) {
        Node first=current.getNextSibling();
        iffirst==null ) return null;
        for (Node node = firstnode != null;
             node = node.getNextSibling()) {
            
            iftype >= 0 && node.getNodeType() != type ) continue;
            //System.out.println("getNode: " + name + " " + node.getNodeName());
            ifname==null )
                return node;
            ifname.equalsnode.getNodeName() ) ) {
                return node;
            }
        }
        return null;
    }
    public static class NullResolver implements EntityResolver {
        public InputSource resolveEntity (String publicId,
                                                   String systemId)
            throws SAXExceptionIOException
        {
            if..isTraceEnabled())
                ..trace("ResolveEntity: " + publicId + " " + systemId);
            return new InputSource(new StringReader(""));
        }
    }
    public static void setAttributesObject oNode parent)
    {
        NamedNodeMap attrs=parent.getAttributes();
        ifattrs==null ) return;
        for (int i=0; i<attrs.getLength(); i++ ) {
            Node n=attrs.item(i);
            String name=n.getNodeName();
            String value=n.getNodeValue();
            if..isTraceEnabled() )
                ..trace("Attribute " + parent.getNodeName() + " " +
                            name + "=" + value);
            try {
                IntrospectionUtils.setProperty(onamevalue);
            } catchException ex ) {
                ex.printStackTrace();
            }
        }
    }

    
Read XML as DOM.
    public static Document readXml(InputStream is)
    {
        DocumentBuilderFactory dbf =
            DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        dbf.setIgnoringComments(false);
        dbf.setIgnoringElementContentWhitespace(true);
        //dbf.setCoalescing(true);
        //dbf.setExpandEntityReferences(true);
        DocumentBuilder db = null;
        db = dbf.newDocumentBuilder();
        db.setEntityResolvernew NullResolver() );
        // db.setErrorHandler( new MyErrorHandler());
        Document doc = db.parse(is);
        return doc;
    }
    public static void writeXmlNode nOutputStream os )
            throws TransformerException
    {
        TransformerFactory tf=TransformerFactory.newInstance();
        //identity
        Transformer t=tf.newTransformer();
        t.setOutputProperty(."yes");
        t.transform(new DOMSourcen ), new StreamResultos ));
    }
New to GrepCode? Check out our FAQ X