Saturday 6 August 2011

Returns the text of the element

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Utils {

  /**
   
   */
  public static String getElementText(Element element) {
      StringBuffer buffer = new StringBuffer();
      NodeList nodeList = element.getChildNodes();
      for (int i = 0; i < nodeList.getLength(); i++) {
          Node node = nodeList.item(i);
          if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) {
              buffer.append(node.getNodeValue());
          }
      }
      return buffer.toString();
  }
}

   
    
  

Returns the first element that has the specified local name.

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Utils {

  public static Element getFirstChild(Element e, String local) {
    forNode n=e.getFirstChild(); n!=null; n=n.getNextSibling() ) {
        if(n.getNodeType()==Node.ELEMENT_NODE) {
            Element c = (Element)n;
            if(c.getLocalName().equals(local))
                return c;
        }
    }
    return null;
}

}

   
    
  

Returns the first child element with the given name.

  

import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Utils {


  /**
   * <p>Returns the first child element with the given name. Returns
   * <code>null</code> if not found.</p>
   *
   @param parent parent element
   @param name name of the child element
   @return child element
   */
  public static Element getChildElementByName(Element parent, String name)
  {
      NodeList children = parent.getChildNodes();

      for(int i = 0; i < children.getLength(); i++) {
          Node node = children.item(i);
          if(node.getNodeType() == Node.ELEMENT_NODE) {
              Element element = (Elementnode;
              if(element.getTagName().equals(name)) {
                  return element;
              }
          }
      }

      return null;
  }

}

   
    
  

Returns text value of a child element. Returns null if there is no child element found.

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class Utils {
  public static String getElementText(Element element)
  {
      StringBuffer buf = new StringBuffer();

      NodeList children = element.getChildNodes();
      for(int i = 0; i < children.getLength(); i++) {
          Node node = children.item(i);
          if(node.getNodeType() == Node.TEXT_NODE ||
             node.getNodeType() == Node.CDATA_SECTION_NODE) {
              Text text = (Textnode;
              buf.append(text.getData().trim());
          }
      }

      return buf.toString();
  }


}

   
    
  

Returns an array of text values of a child element.

  
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class Utils {

  /**
   * <p>Returns an array of text values of a child element. Returns
   * <code>null</code> if there is no child element found.</p>
   *
   @param parent parent element
   @param name name of the child element
   @return text value
   */
  public static String[] getChildElementTextArr(Element parent, String name)
  {
      // Get all the elements
      List children = getChildElementsByName(parent, name);

      String str[] new String[children.size()];

      for(int i = 0; i < children.size(); i++) {
          Node child = (Nodechildren.get(i);

          StringBuffer buf = new StringBuffer();

          NodeList nodes = child.getChildNodes();
          for(int j = 0; j < nodes.getLength(); j++) {
              Node node = nodes.item(j);
              if(node.getNodeType() == Node.TEXT_NODE ||
                 node.getNodeType() == Node.CDATA_SECTION_NODE) {
                  Text text = (Textnode;
                  buf.append(text.getData().trim());
              }
          }

          str[i= buf.toString();
      }

      return str;
  }
  /**
   * <p>Returns a list of child elements with the given
   * name. Returns an empty list if there are no such child
   * elements.</p>
   *
   @param parent parent element
   @param name name of the child element
   @return child elements
   */
  public static List getChildElementsByName(Element parent, String name)
  {
      List elements = new ArrayList();

      NodeList children = parent.getChildNodes();

      for(int i = 0; i < children.getLength(); i++) {
          Node node = children.item(i);
          if(node.getNodeType() == Node.ELEMENT_NODE) {
              Element element = (Elementnode;
              if(element.getTagName().equals(name)) {
                  elements.add(element);
              }
          }
      }

      return elements;
  }

}

   
    
  

Returns a list of child elements with the given name.

  
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class Utils {


  /**
   * <p>Returns a list of child elements with the given
   * name. Returns an empty list if there are no such child
   * elements.</p>
   *
   @param parent parent element
   @param name name of the child element
   @return child elements
   */
  public static List getChildElementsByName(Element parent, String name)
  {
      List elements = new ArrayList();

      NodeList children = parent.getChildNodes();

      for(int i = 0; i < children.getLength(); i++) {
          Node node = children.item(i);
          if(node.getNodeType() == Node.ELEMENT_NODE) {
              Element element = (Elementnode;
              if(element.getTagName().equals(name)) {
                  elements.add(element);
              }
          }
      }

      return elements;
  }

}

   
    
  

Return the first named Element found. Null if none.

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Utils {

  /**
   * Return a list of named Elements.
   @param element the containing Element
   @param name the tag name
   @return NodeList of matching elements
   */
  public static NodeList getElementList(Element element, String name) {
    return element.getElementsByTagName(name);
  }
  /**
   * Return the first named Element found.  Null if none.
   @param element the containing Element
   @param name the tag name
   @return matching Element (null if none)
   */
  public static Element getElement(Element element, String name) {
    NodeList nodeList = getElementList(element, name);
    return (nodeList.getLength() == 0null (ElementnodeList.item(0);
  }

}

   
    
  

Return child elements with specified name.

  
/**
 * 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.
 */

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 * Few simple utils to read DOM. This is originally from the Jakarta Commons
 * Modeler.
 
 @author Costin Manolache
 */
public class Utils {
  /**
   * Return child elements with specified name.
   
   @param parent
   @param ns
   @param localName
   @return
   */
  public static List<Element> getChildrenWithName(Element parent, String ns, String localName) {
    List<Element> r = new ArrayList<Element>();
    for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
      if (instanceof Element) {
        Element e = (Elementn;
        String eNs = (e.getNamespaceURI() == null"" : e.getNamespaceURI();
        if (ns.equals(eNs&& localName.equals(e.getLocalName())) {
          r.add(e);
        }
      }
    }
    return r;
  }
}

   
    
  

Return a list of named Elements.

  
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
*                  Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
*      http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/


import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Utils {

  /**
   * Return a list of named Elements.
   @param element the containing Element
   @param name the tag name
   @return NodeList of matching elements
   */
  public static NodeList getElementList(Element element, String name) {
    return element.getElementsByTagName(name);
  }
  /**
   * Return the first named Element found.  Null if none.
   @param element the containing Element
   @param name the tag name
   @return matching Element (null if none)
   */
  public static Element getElement(Element element, String name) {
    NodeList nodeList = getElementList(element, name);
    return (nodeList.getLength() == 0null (ElementnodeList.item(0);
  }

}

   
    
  

Return a list of named Elements with a specific attribute value.

  
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
*                  Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
*      http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/


import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Utils {
  /**
   * Get an Attribute from an Element.  Returns an empty String if none found
   @param element the containing Element
   @param name the attribute name
   @return Attribute as a String
   */
  public static String getAttribute(Element element, String name) {
    return element.getAttribute(name);
  }
  /**
   * Return a list of named Elements with a specific attribute value.
   @param element the containing Element
   @param name the tag name
   @param attribute Attribute name
   @param value Attribute value
   @param returnFirst Return only the first matching value?
   @return List of matching elements
   */
  public static List selectElementsByAttributeValue(Element element, String name,
                                                    String attribute, String value,
                                                    boolean returnFirst) {
    NodeList  elementList = element.getElementsByTagName(name);
    List      resultList  = new ArrayList();

    for (int i = 0; i < elementList.getLength(); i++) {
      if (getAttribute((ElementelementList.item(i), attribute).equals(value)) {
        resultList.add(elementList.item(i));
        if (returnFirst) {
          break;
        }
      }
    }
    return resultList;
  }
}

   
    
  

DOM helper for root element

  

/**
 
 */
//org.ajax4jsf.builder.xml;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;


import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * This class must read XML file from input stream and can extract body of root
 * element for include into target in generation.
 
 @author shura
 
 */
public class XMLBody {
  private Document xmlDocument;

  private Element rootElement;

  /**
   * Load XML document and parse it into DOM.
   
   @param input
   @throws ParsingException
   */
  public void loadXML(InputStream inputthrows Exception {
    try {
      // Create Document Builder Factory
      DocumentBuilderFactory docFactory = DocumentBuilderFactory
          .newInstance();

      docFactory.setValidating(false);
      // Create Document Builder
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
      
      docBuilder.isValidating();
      
      // Disable loading of external Entityes
      docBuilder.setEntityResolver(new EntityResolver() {
        // Dummi resolver - alvays do nothing
        public InputSource resolveEntity(String publicId, String systemId)
            throws SAXException, IOException {
          return new InputSource(new StringReader(""));
        }

      });

      // open and parse XML-file
      xmlDocument = docBuilder.parse(input);

      // Get Root xmlElement
      rootElement = xmlDocument.getDocumentElement();
    catch (Exception e) {
      throw new Exception("Error load XML ", e);
    }

  }

  /**
   * Check name of root element is as expected.
   
   @param name
   @return
   */
  public boolean isRootName(String name) {
    return rootElement.getNodeName().equals(name);
  }

  public String getDoctype() {
    DocumentType doctype = xmlDocument.getDoctype();
    if (null != doctype) {
      return doctype.getName();
    }
    return null;
  }

  public String getPiblicId() {
    DocumentType doctype = xmlDocument.getDoctype();
    if (null != doctype) {
      return doctype.getPublicId();
    }
    return null;
  }

  public String getRootTypeName() {
    return rootElement.getSchemaTypeInfo().getTypeName();
  }

  public String getContent() throws Exception {
    NodeList childNodes = rootElement.getChildNodes();
    return serializeNodes(childNodes);
  }

  private String serializeNodes(NodeList childNodesthrows Exception {
    DocumentFragment fragment = xmlDocument.createDocumentFragment();
    for (int i = 0; i < childNodes.getLength(); i++) {
      fragment.appendChild(childNodes.item(i).cloneNode(true));
    }
    try {
      TransformerFactory transformerFactory = TransformerFactory
          .newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty("omit-xml-declaration""yes");
      StringWriter out = new StringWriter();
      StreamResult result = new StreamResult(out);
      transformer.transform(new DOMSource(fragment), result);
      return out.toString();

    catch (Exception e) {
      throw new Exception(e);
    }
  }
  
  public String getContent(String xpaththrows Exception{
    XPath path = XPathFactory.newInstance().newXPath();
    NodeList childNodes;
    try {
      childNodes = (NodeListpath.evaluate(xpath, xmlDocument,XPathConstants.NODESET);
    catch (XPathExpressionException e) {
      throw new Exception("Error evaluate xpath",e);
    }
    return serializeNodes(childNodes);
  }
}

   
    
  

DOM Util: get Element Text

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {

  public static String getChildText(Element parent, String childName) {
    NodeList list = parent.getElementsByTagName(childName);
    if (list.getLength() 1) {
      throw new IllegalStateException("Multiple child elements with name " + childName);
    else if (list.getLength() == 0) {
      return null;
    }
    Element child = (Elementlist.item(0);
    return getText(child);
  }

  public static String getText(Element element) {
    StringBuffer buf = new StringBuffer();
    NodeList list = element.getChildNodes();
    boolean found = false;
    for (int i = 0; i < list.getLength(); i++) {
      Node node = list.item(i);
      if (node.getNodeType() == Node.TEXT_NODE) {
        buf.append(node.getNodeValue());
        found = true;
      }
    }
    return found ? buf.toString() null;
  }
}

   
    
  

Has Attribute

  

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class Utils {


  public static boolean hasAttribute(Element element, String value) {
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node node = attributes.item(i);
        if (value.equals(node.getNodeValue())) {
            return true;
        }
    }
    return false;
}

}