Java/XML/DOM Element

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

Add an entity to a specified Element.

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Utils {
  /**
   * Add an entity to a specified Element.
   *    (eg <code>DomUtils.addEntity(element, "nbsp");</code>)
   * @param element the containing element
   * @param entity the entity to add
   */
  public static void addEntity(Element element, String entity) {
    element.appendChild(element.getOwnerDocument().createEntityReference(entity));
  }
}





Add a new element to the given parent

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Utils {
  /**
   * Add a new element to the given parent
   * @param parent the parent Element
   * @param name the child name
   * @return new Element
   */
  public static Element createElement(Element parent, String name) {
    Document document;
    Element element;
    document = parent.getOwnerDocument();
    element  = document.createElement(name);
    parent.appendChild(element);
    return element;
  }
}





Adds the child element with the given text

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Utils {
  public static void addChildElement(Element element, String name, Object textValue) {
    Document document = element.getOwnerDocument();
    Element child = document.createElement(name);
    element.appendChild(child);
    if (textValue != null) {
      String text = textValue.toString();
      child.appendChild(document.createTextNode(text));
    }
  }
}





Add Text object to an Element.

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Utils {
  /**
   * Add Text object to an Element.
   * @param element the containing element
   * @param text the text to add
   */
  public static void addText(Element element, String text) {
    element.appendChild(element.getOwnerDocument().createTextNode(text));
  }
}





Clean text from Node

  
/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Ant", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
import java.util.Vector;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 
 * @author Abey Mullassery
 * 
 */
public class Main {
  public static void cleanText(Node node) {
    try {
      NodeList childNodes = node.getChildNodes();
      int noChildren = childNodes.getLength();
      Node n = null;
      short type = 0;
      Vector rem = new Vector();
      for (int i = 0; i < noChildren; i++) {
        n = childNodes.item(i);
        type = n.getNodeType();
        if (type == Node.TEXT_NODE) {
          rem.add(n);
        } else if (type == Node.ELEMENT_NODE) {
          cleanText(n);
        }
      }
      for (int i = 0; i < rem.size(); i++) {
        node.removeChild((Node) rem.get(i));
      }
    } catch (Exception e) {
      //DebugUtil.debug(e);
    }
  }
}





Compare two DOM Nodes

  
/**
 *  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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
 * @version $Rev: 514087 $ $Date: 2007-03-03 01:13:40 -0500 (Sat, 03 Mar 2007) $
 */
public class DOMUtils {
  private static void trimEmptyTextNodes(Node node) {
    Element element = null;
    if (node instanceof Document) {
      element = ((Document) node).getDocumentElement();
    } else if (node instanceof Element) {
      element = (Element) node;
    } else {
      return;
    }
    List<Node> nodesToRemove = new ArrayList<Node>();
    NodeList children = element.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
      Node child = children.item(i);
      if (child instanceof Element) {
        trimEmptyTextNodes(child);
      } else if (child instanceof Text) {
        Text t = (Text) child;
        if (t.getData().trim().length() == 0) {
          nodesToRemove.add(child);
        }
      }
    }
    for (Node n : nodesToRemove) {
      element.removeChild(n);
    }
  }
  public static void compareNodes(Node expected, Node actual, boolean trimEmptyTextNodes)
      throws Exception {
    if (trimEmptyTextNodes) {
      trimEmptyTextNodes(expected);
      trimEmptyTextNodes(actual);
    }
    compareNodes(expected, actual);
  }
  public static void compareNodes(Node expected, Node actual) throws Exception {
    if (expected.getNodeType() != actual.getNodeType()) {
      throw new Exception("Different types of nodes: " + expected + " " + actual);
    }
    if (expected instanceof Document) {
      Document expectedDoc = (Document) expected;
      Document actualDoc = (Document) actual;
      compareNodes(expectedDoc.getDocumentElement(), actualDoc.getDocumentElement());
    } else if (expected instanceof Element) {
      Element expectedElement = (Element) expected;
      Element actualElement = (Element) actual;
      // compare element names
      if (!expectedElement.getLocalName().equals(actualElement.getLocalName())) {
        throw new Exception("Element names do not match: " + expectedElement.getLocalName() + " "
            + actualElement.getLocalName());
      }
      // compare element ns
      String expectedNS = expectedElement.getNamespaceURI();
      String actualNS = actualElement.getNamespaceURI();
      if ((expectedNS == null && actualNS != null)
          || (expectedNS != null && !expectedNS.equals(actualNS))) {
        throw new Exception("Element namespaces names do not match: " + expectedNS + " " + actualNS);
      }
      String elementName = "{" + expectedElement.getNamespaceURI() + "}"
          + actualElement.getLocalName();
      // compare attributes
      NamedNodeMap expectedAttrs = expectedElement.getAttributes();
      NamedNodeMap actualAttrs = actualElement.getAttributes();
      if (countNonNamespaceAttribures(expectedAttrs) != countNonNamespaceAttribures(actualAttrs)) {
        throw new Exception(elementName + ": Number of attributes do not match up: "
            + countNonNamespaceAttribures(expectedAttrs) + " "
            + countNonNamespaceAttribures(actualAttrs));
      }
      for (int i = 0; i < expectedAttrs.getLength(); i++) {
        Attr expectedAttr = (Attr) expectedAttrs.item(i);
        if (expectedAttr.getName().startsWith("xmlns")) {
          continue;
        }
        Attr actualAttr = null;
        if (expectedAttr.getNamespaceURI() == null) {
          actualAttr = (Attr) actualAttrs.getNamedItem(expectedAttr.getName());
        } else {
          actualAttr = (Attr) actualAttrs.getNamedItemNS(expectedAttr.getNamespaceURI(),
              expectedAttr.getLocalName());
        }
        if (actualAttr == null) {
          throw new Exception(elementName + ": No attribute found:" + expectedAttr);
        }
        if (!expectedAttr.getValue().equals(actualAttr.getValue())) {
          throw new Exception(elementName + ": Attribute values do not match: "
              + expectedAttr.getValue() + " " + actualAttr.getValue());
        }
      }
      // compare children
      NodeList expectedChildren = expectedElement.getChildNodes();
      NodeList actualChildren = actualElement.getChildNodes();
      if (expectedChildren.getLength() != actualChildren.getLength()) {
        throw new Exception(elementName + ": Number of children do not match up: "
            + expectedChildren.getLength() + " " + actualChildren.getLength());
      }
      for (int i = 0; i < expectedChildren.getLength(); i++) {
        Node expectedChild = expectedChildren.item(i);
        Node actualChild = actualChildren.item(i);
        compareNodes(expectedChild, actualChild);
      }
    } else if (expected instanceof Text) {
      String expectedData = ((Text) expected).getData().trim();
      String actualData = ((Text) actual).getData().trim();
      if (!expectedData.equals(actualData)) {
        throw new Exception("Text does not match: " + expectedData + " " + actualData);
      }
    }
  }
  private static int countNonNamespaceAttribures(NamedNodeMap attrs) {
    int n = 0;
    for (int i = 0; i < attrs.getLength(); i++) {
      Attr attr = (Attr) attrs.item(i);
      if (!attr.getName().startsWith("xmlns")) {
        n++;
      }
    }
    return n;
  }
}





Compare two DOM Nodes from JBoss

  
/**
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
 * @author 
 * @version <tt>$Revision: 3282 $</tt> $Id: XMLUtil.java 3282 2007-11-01
 *          15:32:29Z timfox $
 */
public class Utils {
  public static void assertEquivalent(Node node, Node node2) {
    if (node == null) {
      throw new IllegalArgumentException("the first node to be compared is null");
    }
    if (node2 == null) {
      throw new IllegalArgumentException("the second node to be compared is null");
    }
    if (!node.getNodeName().equals(node2.getNodeName())) {
      throw new IllegalArgumentException("nodes have different node names");
    }
    int attrCount = 0;
    NamedNodeMap attrs = node.getAttributes();
    if (attrs != null) {
      attrCount = attrs.getLength();
    }
    int attrCount2 = 0;
    NamedNodeMap attrs2 = node2.getAttributes();
    if (attrs2 != null) {
      attrCount2 = attrs2.getLength();
    }
    if (attrCount != attrCount2) {
      throw new IllegalArgumentException("nodes hava a different number of attributes");
    }
    outer: for (int i = 0; i < attrCount; i++) {
      Node n = attrs.item(i);
      String name = n.getNodeName();
      String value = n.getNodeValue();
      for (int j = 0; j < attrCount; j++) {
        Node n2 = attrs2.item(j);
        String name2 = n2.getNodeName();
        String value2 = n2.getNodeValue();
        if (name.equals(name2) && value.equals(value2)) {
          continue outer;
        }
      }
      throw new IllegalArgumentException("attribute " + name + "=" + value + " doesn"t match");
    }
    boolean hasChildren = node.hasChildNodes();
    if (hasChildren != node2.hasChildNodes()) {
      throw new IllegalArgumentException("one node has children and the other doesn"t");
    }
    if (hasChildren) {
      NodeList nl = node.getChildNodes();
      NodeList nl2 = node2.getChildNodes();
      short[] toFilter = new short[] { Node.TEXT_NODE, Node.ATTRIBUTE_NODE, Node.ruMENT_NODE };
      List nodes = filter(nl, toFilter);
      List nodes2 = filter(nl2, toFilter);
      int length = nodes.size();
      if (length != nodes2.size()) {
        throw new IllegalArgumentException("nodes hava a different number of children");
      }
      for (int i = 0; i < length; i++) {
        Node n = (Node) nodes.get(i);
        Node n2 = (Node) nodes2.get(i);
        assertEquivalent(n, n2);
      }
    }
  }
  private static List filter(NodeList nl, short[] typesToFilter) {
    List nodes = new ArrayList();
    outer: for (int i = 0; i < nl.getLength(); i++) {
      Node n = nl.item(i);
      short type = n.getNodeType();
      for (int j = 0; j < typesToFilter.length; j++) {
        if (typesToFilter[j] == type) {
          continue outer;
        }
      }
      nodes.add(n);
    }
    return nodes;
  }
}





Convert Element To Stream

 
import java.io.OutputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Element;
public class Main {
  public static void ElementToStream(Element element, OutputStream out) {
    try {
      DOMSource source = new DOMSource(element);
      StreamResult result = new StreamResult(out);
      TransformerFactory transFactory = TransformerFactory.newInstance();
      Transformer transformer = transFactory.newTransformer();
      transformer.transform(source, result);
    } catch (Exception ex) {
    }
  }
}





Convert node element To String

 
/**
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
 * @author 
 * @version <tt>$Revision: 3282 $</tt> $Id: XMLUtil.java 3282 2007-11-01
 *          15:32:29Z timfox $
 */
public class Utils {
  public static String elementToString(Node n) {
    String name = n.getNodeName();
    short type = n.getNodeType();
    if (Node.CDATA_SECTION_NODE == type) {
      return "<![CDATA[" + n.getNodeValue() + "]]&gt;";
    }
    if (name.startsWith("#")) {
      return "";
    }
    StringBuffer sb = new StringBuffer();
    sb.append("<").append(name);
    NamedNodeMap attrs = n.getAttributes();
    if (attrs != null) {
      for (int i = 0; i < attrs.getLength(); i++) {
        Node attr = attrs.item(i);
        sb.append(" ").append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append(
            "\"");
      }
    }
    String textContent = null;
    NodeList children = n.getChildNodes();
    if (children.getLength() == 0) {
      if ((textContent = XMLUtil.getTextContent(n)) != null && !"".equals(textContent)) {
        sb.append(textContent).append("</").append(name).append(">");
        ;
      } else {
        sb.append("/>").append("\n");
      }
    } else {
      sb.append(">").append("\n");
      boolean hasValidChildren = false;
      for (int i = 0; i < children.getLength(); i++) {
        String childToString = elementToString(children.item(i));
        if (!"".equals(childToString)) {
          sb.append(childToString);
          hasValidChildren = true;
        }
      }
      if (!hasValidChildren && ((textContent = XMLUtil.getTextContent(n)) != null)) {
        sb.append(textContent);
      }
      sb.append("</").append(name).append(">");
    }
    return sb.toString();
  }
}





Create a new element

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Utils {
  /**
   * Create a new element
   * @param document Document to contain the new element
   * @param name the element name
   * @return new Element
   */
  public static Element createElement(Document document, String name) {
    Element element;
    return document.createElement(name);
  }
}





Create New Container

  
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Element createNewContainer(Document document, Element parent,
      String childElement) {
    Element child = (Element) document.createElement(childElement);
    parent.appendChild(child);
    return child;
  }
}





Create New Element And Set

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Element createNewElementAndSet(Document document,
      Element parent, String childElement, String childValue) {
    Element child = (Element) document.createElement(childElement);
    parent.appendChild(child);
    child.setNodeValue(childValue);
    child.appendChild(document.createTextNode(childValue));
    return child;
  }
}





Create New Element And Set Attribute

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Element createNewElementAndSetAndAttribute(Document document,
      Element parent, String childElement, String childValue,
      String attributeName, String attributeValue) {
    Element child = createNewElementAndSet(document, parent, childElement,
        childValue);
    child.setAttribute(attributeName, attributeValue);
    return child;
  }
  public static Element createNewElementAndSet(Document document,
      Element parent, String childElement, String childValue) {
    Element child = (Element) document.createElement(childElement);
    parent.appendChild(child);
    child.setNodeValue(childValue);
    child.appendChild(document.createTextNode(childValue));
    return child;
  }
}





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 input) throws 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 childNodes) throws 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 xpath) throws Exception{
    XPath path = XPathFactory.newInstance().newXPath();
    NodeList childNodes;
    try {
      childNodes = (NodeList) path.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 = (Element) list.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;
  }
}





Find All Elements By Tag 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.LinkedList;
import java.util.List;
import javax.xml.namespace.QName;
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 {
  public static List<Element> findAllElementsByTagName(Element elem, String tagName) {
    List<Element> ret = new LinkedList<Element>();
    findAllElementsByTagName(elem, tagName, ret);
    return ret;
}
  private static void findAllElementsByTagName(Element el, String tagName, List<Element> elementList) {
    if (tagName.equals(el.getTagName())) {
      elementList.add(el);
    }
    Element elem = getFirstElement(el);
    while (elem != null) {
      findAllElementsByTagName(elem, tagName, elementList);
      elem = getNextElement(elem);
    }
  }
  private static void findAllElementsByTagNameNS(Element el, String nameSpaceURI, String localName,
      List<Element> elementList) {
    if (localName.equals(el.getLocalName()) && nameSpaceURI.contains(el.getNamespaceURI())) {
      elementList.add(el);
    }
    Element elem = getFirstElement(el);
    while (elem != null) {
      findAllElementsByTagNameNS(elem, nameSpaceURI, localName, elementList);
      elem = getNextElement(elem);
    }
  }
  public static Element getFirstElement(Node parent) {
    Node n = parent.getFirstChild();
    while (n != null && Node.ELEMENT_NODE != n.getNodeType()) {
      n = n.getNextSibling();
    }
    if (n == null) {
      return null;
    }
    return (Element) n;
  }
  public static Element getNextElement(Element el) {
    Node nd = el.getNextSibling();
    while (nd != null) {
      if (nd.getNodeType() == Node.ELEMENT_NODE) {
        return (Element) nd;
      }
      nd = nd.getNextSibling();
    }
    return null;
  }
}





Find All Elements By Tag Name Name Space

  
/**
 * 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.LinkedList;
import java.util.List;
import javax.xml.namespace.QName;
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 {
  public static List<Element> findAllElementsByTagNameNS(Element elem, String nameSpaceURI,
      String localName) {
    List<Element> ret = new LinkedList<Element>();
    findAllElementsByTagNameNS(elem, nameSpaceURI, localName, ret);
    return ret;
  }
  private static void findAllElementsByTagName(Element el, String tagName, List<Element> elementList) {
    if (tagName.equals(el.getTagName())) {
      elementList.add(el);
    }
    Element elem = getFirstElement(el);
    while (elem != null) {
      findAllElementsByTagName(elem, tagName, elementList);
      elem = getNextElement(elem);
    }
  }
  private static void findAllElementsByTagNameNS(Element el, String nameSpaceURI, String localName,
      List<Element> elementList) {
    if (localName.equals(el.getLocalName()) && nameSpaceURI.contains(el.getNamespaceURI())) {
      elementList.add(el);
    }
    Element elem = getFirstElement(el);
    while (elem != null) {
      findAllElementsByTagNameNS(elem, nameSpaceURI, localName, elementList);
      elem = getNextElement(elem);
    }
  }
  public static Element getFirstElement(Node parent) {
    Node n = parent.getFirstChild();
    while (n != null && Node.ELEMENT_NODE != n.getNodeType()) {
      n = n.getNextSibling();
    }
    if (n == null) {
      return null;
    }
    return (Element) n;
  }
  public static Element getNextElement(Element el) {
    Node nd = el.getNextSibling();
    while (nd != null) {
      if (nd.getNodeType() == Node.ELEMENT_NODE) {
        return (Element) nd;
      }
      nd = nd.getNextSibling();
    }
    return null;
  }
}





Find Container Else Create One

  
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Element findContainerElseCreate(Document document,
      Element parent, String child) {
    NodeList nl = parent.getElementsByTagName(child);
    if (nl.getLength() == 0) {
      parent.appendChild(document.createElement(child));
    }
    return (Element) parent.getElementsByTagName(child).item(0);
  }
}





Find Element And Set Or Create And Set

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Element findElementAndSetElseCreateAndSet(Document document,
      Element parent, String child, boolean value) {
    return findElementAndSetElseCreateAndSet(document, parent, child, ""
        + value);
  }
  public static Element findElementAndSetElseCreateAndSet(Document document,
      Element parent, String child, float value) {
    return findElementAndSetElseCreateAndSet(document, parent, child, ""
        + value);
  }
  public static Element findElementAndSetElseCreateAndSet(Document document,
      Element parent, String element, Date date) {
    return findElementAndSetElseCreateAndSet(document, parent, element,
        getDateString(date));
  }
  public static Element findElementAndSetElseCreateAndSet(Document document,
      Element parent, String child, String value) {
    NodeList nl = parent.getElementsByTagName(child);
    if (nl.getLength() == 0) {
      parent.appendChild(document.createElement(child));
    }
    Element ret = (Element) parent.getElementsByTagName(child).item(0);
    if (ret.getFirstChild() != null) {
      ret.removeChild(ret.getFirstChild());
    }
    ret.appendChild(document.createTextNode(value));
    return ret;
  }
}





Find Element Or Container

  
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Element findElementOrContainer(Document document,
      Element parent, String element) {
    NodeList nl = parent.getElementsByTagName(element);
    if (nl.getLength() == 0) {
      return null;
    }
    return (Element) nl.item(0);
  }
}





Find Element Or Create And Attribute

  
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Element findElementElseCreateAndAttribute(Document document,
      Element parent, String element, String attributeName,
      String attributeValue) {
    NodeList nl = parent.getElementsByTagName(element);
    Element e = null;
    if (nl.getLength() == 0) {
      parent.appendChild(document.createElement(element));
      e = (Element) parent.getElementsByTagName(element).item(0);
      e.setAttribute(attributeName, attributeValue);
    }
    return e;
  }
}





Find Element Or Create And Set

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Element findElementElseCreateAndSet(Document document,
      Element parent, String child, String value) {
    Element ret = null;
    NodeList nl = parent.getElementsByTagName(child);
    if (nl.getLength() == 0) {
      parent.appendChild(document.createElement(child));
      ret = (Element) parent.getElementsByTagName(child).item(0);
      ret.appendChild(document.createTextNode(value));
    }
    return ret;
  }
}





Find Element Or Create And Set Attribute

  
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Element findElementElseCreateAndSetAndAttribute(
      Document document, Element parent, String element, String value,
      String attributeName, String attributeValue) {
    Element e = findElementElseCreateAndAttribute(document, parent,
        element, attributeName, attributeValue);
    if (e != null)
      e.appendChild(document.createTextNode(value));
    return e;
  }
  public static Element findElementElseCreateAndAttribute(Document document,
      Element parent, String element, String attributeName,
      String attributeValue) {
    NodeList nl = parent.getElementsByTagName(element);
    Element e = null;
    if (nl.getLength() == 0) {
      parent.appendChild(document.createElement(element));
      e = (Element) parent.getElementsByTagName(element).item(0);
      e.setAttribute(attributeName, attributeValue);
    }
    return e;
  }
}





Get child from an element by name

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Main {
  public static String getChildContent(Element parent, String name, String missing, String empty) {
    Element child = getChild(parent, name);
    if (child == null) {
      return missing;
    } else {
      String content = (String) getContent(child);
      return (content != null) ? content : empty;
    }
  }
  public static Object getContent(Element element) {
    NodeList nl = element.getChildNodes();
    StringBuffer content = new StringBuffer();
    for (int i = 0; i < nl.getLength(); i++) {
      Node node = nl.item(i);
      switch (node.getNodeType()) {
      case Node.ELEMENT_NODE:
        return node;
      case Node.CDATA_SECTION_NODE:
      case Node.TEXT_NODE:
        content.append(node.getNodeValue());
        break;
      }
    }
    return content.toString().trim();
  }
  public static Element getChild(Element parent, String name) {
    for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
      if (child instanceof Element && name.equals(child.getNodeName())) {
        return (Element) child;
      }
    }
    return null;
  }
}





Get content from element

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Main {
  public static String getChildContent(Element parent, String name, String missing, String empty) {
    Element child = getChild(parent, name);
    if (child == null) {
      return missing;
    } else {
      String content = (String) getContent(child);
      return (content != null) ? content : empty;
    }
  }
  public static Object getContent(Element element) {
    NodeList nl = element.getChildNodes();
    StringBuffer content = new StringBuffer();
    for (int i = 0; i < nl.getLength(); i++) {
      Node node = nl.item(i);
      switch (node.getNodeType()) {
      case Node.ELEMENT_NODE:
        return node;
      case Node.CDATA_SECTION_NODE:
      case Node.TEXT_NODE:
        content.append(node.getNodeValue());
        break;
      }
    }
    return content.toString().trim();
  }
  public static Element getChild(Element parent, String name) {
    for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
      if (child instanceof Element && name.equals(child.getNodeName())) {
        return (Element) child;
      }
    }
    return null;
  }
}





Get Element Boolean Value

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static boolean getElementBooleanValue(Document document,
      Element parent, String element) {
    return Boolean
        .valueOf(getElementStringValue(document, parent, element))
        .booleanValue();
  }
  public static String getElementStringValue(Document document,
      Element parent, String element) {
    NodeList nl = parent.getElementsByTagName(element);
    if (nl.getLength() == 0) {
      return "";
    }
    Node n = nl.item(0).getFirstChild();
    if (n == null) {
      return "";
    }
    return n.getNodeValue();
  }
}





Get Element Date Value

  
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Date getElementDateValue(Document document, Element parent, String string) {
    return parseDate(getElementStringValue(document, parent, string));
  }
  private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"T"HH:mm:ss");
  public static Date parseDate(String date) {
    try {
      return sdf.parse(date);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    return null;
  }
  public static String getElementStringValue(Document document, Element parent, String element) {
    NodeList nl = parent.getElementsByTagName(element);
    if (nl.getLength() == 0) {
      return "";
    }
    Node n = nl.item(0).getFirstChild();
    if (n == null) {
      return "";
    }
    return n.getNodeValue();
  }
}





Get Element Float Value

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static float getElementFloatValue(Document document, Element parent,
      String element) {
    return Float
        .parseFloat(getElementStringValue(document, parent, element));
  }
  public static String getElementStringValue(Document document,
      Element parent, String element) {
    NodeList nl = parent.getElementsByTagName(element);
    if (nl.getLength() == 0) {
      return "";
    }
    Node n = nl.item(0).getFirstChild();
    if (n == null) {
      return "";
    }
    return n.getNodeValue();
  }
}





Get Element Int Value

  
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static int getElementIntValue(Document document, Element parent,
      String string) {
    return Integer
        .parseInt(getElementStringValue(document, parent, string));
  }
  public static String getElementStringValue(Document document, Element parent, String element) {
    NodeList nl = parent.getElementsByTagName(element);
    if (nl.getLength() == 0) {
      return "";
    }
    Node n = nl.item(0).getFirstChild();
    if (n == null) {
      return "";
    }
    return n.getNodeValue();
  }
}





Get Element Long Value

  
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static long getElementLongValue(Document document, Element parent,
      String string) {
    return Long.parseLong(getElementStringValue(document, parent, string));
  }
  public static String getElementStringValue(Document document, Element parent, String element) {
    NodeList nl = parent.getElementsByTagName(element);
    if (nl.getLength() == 0) {
      return "";
    }
    Node n = nl.item(0).getFirstChild();
    if (n == null) {
      return "";
    }
    return n.getNodeValue();
  }
}





Get Element QName

  
/**
 * 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 javax.xml.namespace.QName;
import org.w3c.dom.Element;
/**
 * Few simple utils to read DOM. This is originally from the Jakarta Commons
 * Modeler.
 * 
 * @author Costin Manolache
 */
public class Utils {
  public static QName getElementQName(Element el) {
    return new QName(el.getNamespaceURI(), el.getLocalName());
}
}





Get Elements by parent element

  
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static Element[] getElements(Document document, Element parent) {
    if (parent == null) {
      return new Element[] {};
    }
    NodeList nl = parent.getChildNodes();
    ArrayList al = new ArrayList();
    for (int i = 0; i < nl.getLength(); i++) {
      Node n = nl.item(i);
      if (n instanceof Element) {
        al.add((Element) nl.item(i));
      }
    }
    Element[] ret = new Element[al.size()];
    Iterator it = al.iterator();
    int i = 0;
    while (it.hasNext()) {
      ret[i] = (Element) it.next();
      i++;
    }
    return ret;
  }
}





Get Element String Value

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static String getElementStringValue(Document document,
      Element parent, String element) {
    NodeList nl = parent.getElementsByTagName(element);
    if (nl.getLength() == 0) {
      return "";
    }
    Node n = nl.item(0).getFirstChild();
    if (n == null) {
      return "";
    }
    return n.getNodeValue();
  }
}





Get Element Text

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Utils {
  public static String getElementText(Element e) {
    StringBuffer buf = new StringBuffer();
    for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling()) {
      if (n.getNodeType() == Node.TEXT_NODE || n.getNodeType() == Node.CDATA_SECTION_NODE) {
        buf.append(n.getNodeValue());
      }
    }
    return buf.toString();
  }
}





Get First Element

  
/**
 * 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 javax.xml.namespace.QName;
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 {
  public static Element getFirstElement(Node parent) {
    Node n = parent.getFirstChild();
    while (n != null && Node.ELEMENT_NODE != n.getNodeType()) {
        n = n.getNextSibling();
    }
    if (n == null) {
        return null;
    }
    return (Element)n;
}
  public static Element getNextElement(Element el) {
    Node nd = el.getNextSibling();
    while (nd != null) {
        if (nd.getNodeType() == Node.ELEMENT_NODE) {
            return (Element)nd;
        }
        nd = nd.getNextSibling();
    }
    return null;
}
}





Get Next Element

  
/**
 * 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 javax.xml.namespace.QName;
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 {
  public static Element getNextElement(Element el) {
    Node nd = el.getNextSibling();
    while (nd != null) {
        if (nd.getNodeType() == Node.ELEMENT_NODE) {
            return (Element)nd;
        }
        nd = nd.getNextSibling();
    }
    return null;
}
}





Get the content of an optional child element

  
import java.util.ArrayList;
import java.util.Iterator;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
 * A utility class to cover up the rough bits of xml parsing
 * 
 * @author 
 * @version $Revision: 70500 $
 */
public class XmlHelper {
  /**
   * Macro to get the content of an optional child element.
   * 
   * @param element
   *          The parent element.
   * @param tagName
   *          The name of the desired child.
   * @return The element content or null.
   */
  public static String getOptionalChildContent(Element element, String tagName) throws Exception {
    return getElementContent(getOptionalChild(element, tagName));
  }
  public static boolean getOptionalChildBooleanContent(Element element, String name)
      throws Exception {
    Element child = getOptionalChild(element, name);
    if (child != null) {
      String value = getElementContent(child).toLowerCase();
      return value.equals("true") || value.equals("yes");
    }
    return false;
  }
  /**
   * Returns an iterator over the children of the given element with the given
   * tag name.
   * 
   * @param element
   *          The parent element
   * @param tagName
   *          The name of the desired child
   * @return An interator of children or null if element is null.
   */
  public static Iterator<Element> getChildrenByTagName(Element element, String tagName) {
    if (element == null)
      return null;
    // getElementsByTagName gives the corresponding elements in the whole
    // descendance. We want only children
    NodeList children = element.getChildNodes();
    ArrayList<Element> goodChildren = new ArrayList<Element>();
    for (int i = 0; i < children.getLength(); i++) {
      Node currentChild = children.item(i);
      if (currentChild.getNodeType() == Node.ELEMENT_NODE
          && ((Element) currentChild).getTagName().equals(tagName)) {
        goodChildren.add((Element) currentChild);
      }
    }
    return goodChildren.iterator();
  }
  /**
   * Gets the child of the specified element having the specified unique name.
   * If there are more than one children elements with the same name and
   * exception is thrown.
   * 
   * @param element
   *          The parent element
   * @param tagName
   *          The name of the desired child
   * @return The named child.
   * 
   * @throws Exception
   *           Child was not found or was not unique.
   */
  public static Element getUniqueChild(Element element, String tagName) throws Exception {
    Iterator<Element> goodChildren = getChildrenByTagName(element, tagName);
    if (goodChildren != null && goodChildren.hasNext()) {
      Element child = goodChildren.next();
      if (goodChildren.hasNext()) {
        throw new Exception("expected only one " + tagName + " tag");
      }
      return child;
    } else {
      throw new Exception("expected one " + tagName + " tag");
    }
  }
  /**
   * Gets the child of the specified element having the specified name. If the
   * child with this name doesn"t exist then null is returned instead.
   * 
   * @param element
   *          the parent element
   * @param tagName
   *          the name of the desired child
   * @return either the named child or null
   */
  public static Element getOptionalChild(Element element, String tagName) throws Exception {
    return getOptionalChild(element, tagName, null);
  }
  /**
   * Gets the child of the specified element having the specified name. If the
   * child with this name doesn"t exist then the supplied default element is
   * returned instead.
   * 
   * @param element
   *          the parent element
   * @param tagName
   *          the name of the desired child
   * @param defaultElement
   *          the element to return if the child doesn"t exist
   * @return either the named child or the supplied default
   */
  public static Element getOptionalChild(Element element, String tagName, Element defaultElement)
      throws Exception {
    Iterator<Element> goodChildren = getChildrenByTagName(element, tagName);
    if (goodChildren != null && goodChildren.hasNext()) {
      Element child = goodChildren.next();
      if (goodChildren.hasNext()) {
        throw new Exception("expected only one " + tagName + " tag");
      }
      return child;
    } else {
      return defaultElement;
    }
  }
  /**
   * Get the content of the given element.
   * 
   * @param element
   *          The element to get the content for.
   * @return The content of the element or null.
   */
  public static String getElementContent(final Element element) throws Exception {
    return getElementContent(element, null);
  }
  /**
   * Get the content of the given element.
   * 
   * @param element
   *          The element to get the content for.
   * @param defaultStr
   *          The default to return when there is no content.
   * @return The content of the element or the default.
   */
  public static String getElementContent(Element element, String defaultStr) throws Exception {
    if (element == null)
      return defaultStr;
    NodeList children = element.getChildNodes();
    String result = "";
    for (int i = 0; i < children.getLength(); i++) {
      if (children.item(i).getNodeType() == Node.TEXT_NODE
          || children.item(i).getNodeType() == Node.CDATA_SECTION_NODE) {
        result += children.item(i).getNodeValue();
      } else if (children.item(i).getNodeType() == Node.ruMENT_NODE) {
        // Ignore comment nodes
      }
    }
    return result.trim();
  }
  /**
   * Macro to get the content of a unique child element.
   * 
   * @param element
   *          The parent element.
   * @param tagName
   *          The name of the desired child.
   * @return The element content or null.
   */
  public static String getUniqueChildContent(Element element, String tagName) throws Exception {
    return getElementContent(getUniqueChild(element, tagName));
  }
}





Get the content of the given element.

  
import java.util.ArrayList;
import java.util.Iterator;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
public class Utils {

  /**
   * Get the content of the given element.
   *
   * @param element       The element to get the content for.
   * @param defaultStr    The default to return when there is no content.
   * @return              The content of the element or the default.
   */
  public static String getElementContent(Element element, String defaultStr)
     throws Exception
  {
     if (element == null)
        return defaultStr;
     NodeList children = element.getChildNodes();
     String result = "";
     for (int i = 0; i < children.getLength(); i++)
     {
        if (children.item(i).getNodeType() == Node.TEXT_NODE || 
            children.item(i).getNodeType() == Node.CDATA_SECTION_NODE)
        {
           result += children.item(i).getNodeValue();
        }
        else if( children.item(i).getNodeType() == Node.ruMENT_NODE )
        {
           // Ignore comment nodes
        }
     }
     return result.trim();
  }
  /**
   * Gets the child of the specified element having the specified unique
   * name.  If there are more than one children elements with the same name
   * and exception is thrown.
   *
   * @param element    The parent element
   * @param tagName    The name of the desired child
   * @return           The named child.
   *
   * @throws Exception   Child was not found or was not unique.
   */
  public static Element getUniqueChild(Element element, String tagName)
     throws Exception
  {
     Iterator<Element> goodChildren = getChildrenByTagName(element, tagName);
     if (goodChildren != null && goodChildren.hasNext()) {
        Element child = goodChildren.next();
        if (goodChildren.hasNext()) {
           throw new Exception
              ("expected only one " + tagName + " tag");
        }
        return child;
     } else {
        throw new Exception
           ("expected one " + tagName + " tag");
     }
  }
  /**
   * Returns an iterator over the children of the given element with
   * the given tag name.
   *
   * @param element    The parent element
   * @param tagName    The name of the desired child
   * @return           An interator of children or null if element is null.
   */
  public static Iterator<Element> getChildrenByTagName(Element element,
                                              String tagName)
  {
     if (element == null) return null;
     // getElementsByTagName gives the corresponding elements in the whole 
     // descendance. We want only children
     NodeList children = element.getChildNodes();
     ArrayList<Element> goodChildren = new ArrayList<Element>();
     for (int i=0; i<children.getLength(); i++) {
        Node currentChild = children.item(i);
        if (currentChild.getNodeType() == Node.ELEMENT_NODE && 
            ((Element)currentChild).getTagName().equals(tagName)) {
           goodChildren.add((Element)currentChild);
        }
     }
     return goodChildren.iterator();
  }
}





Get the first child element

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Utils {
  /**
   * Get the first child element
   * @param parent
   * @return
   */
  public static Element getFirstChildElement(Node parent) {
      NodeList childs = parent.getChildNodes();
      for (int i = 0; i < childs.getLength(); i++) {
          Node child = childs.item(i);
          if (child instanceof Element) {
              return (Element) child;
          }
      }
      return null;
  }
}





Get the first element child.

 
/**
 * 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.io.OutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
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 {
  /**
   * Get the first element child.
   * 
   * @param parent lookup direct childs
   * @param name name of the element. If null return the first element.
   */
  public static Node getChild(Node parent, String name) {
      if (parent == null) {
          return null;
      }
      Node first = parent.getFirstChild();
      if (first == null) {
          return null;
      }
      for (Node node = first; node != null; node = node.getNextSibling()) {
          // System.out.println("getNode: " + name + " " +
          // node.getNodeName());
          if (node.getNodeType() != Node.ELEMENT_NODE) {
              continue;
          }
          if (name != null && name.equals(node.getNodeName())) {
              return node;
          }
          if (name == null) {
              return node;
          }
      }
      return null;
  }
}





Get the first text node associated with this element

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Utils {
  public static String getFirstText(Node parent) {
    return getTextNodeByNumber(parent, 1);
  }
  public static String getTextNodeByNumber(Node parent, int number) {
    String  text  = null;
    int     count = 1;
    if (parent != null) {
      for (Node child = parent.getFirstChild();
                child != null;
                child = child.getNextSibling()) {
        if ((child.getNodeType() == Node.TEXT_NODE) && (count++ == number)) {
          text = child.getNodeValue();
          return text.trim();
        }
      }
    }
    return text;
  }
}





Get the next sibling element

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Utils {
  /**
   * Get the next sibling element
   * @param el
   * @return
   */
  public static Element getNextSiblingElement(Element el) {
      for (Node n = el.getNextSibling(); n != null; n = n.getNextSibling()) {
          if (n instanceof Element) {
              return (Element) n;
          }
      }
      return null;
  }
}





Get the next sibling with the same name and type

  
import org.w3c.dom.Node;
public class Utils {
  /**
   * Get the next sibling with the same name and type
   */
  public static Node getNext(Node current) {
      String name = current.getNodeName();
      int type = current.getNodeType();
      return getNext(current, name, type);
  }
  /**
   * Return the next sibling with a given name and type
   */
  public static Node getNext(Node current, String name, int type) {
      Node first = current.getNextSibling();
      if (first == null) {
          return null;
      }
      for (Node node = first; node != null; node = node.getNextSibling()) {
          if (type >= 0 && node.getNodeType() != type) {
              continue;
          }
          if (name == null) {
              return node;
          }
          if (name.equals(node.getNodeName())) {
              return node;
          }
      }
      return null;
  }
  /**
   * Get the first child of the specified type.
   * 
   * @param parent
   * @param type
   * @return
   */
  public static Node getChild(Node parent, int type) {
      Node n = parent.getFirstChild();
      while (n != null && type != n.getNodeType()) {
          n = n.getNextSibling();
      }
      if (n == null) {
          return null;
      }
      return n;
  }

}





Get the raw text content of a node or null if there is no text

  
import org.w3c.dom.Node;
public class Utils {

  /**
   * Get the raw text content of a node or null if there is no text
   */
  public static String getRawContent(Node n) {
      if (n == null) {
          return null;
      }
      Node n1 = getChild(n, Node.TEXT_NODE);
      if (n1 == null) {
          return null;
      }
      return n1.getNodeValue();
  }
  /**
   * Get the first child of the specified type.
   * 
   * @param parent
   * @param type
   * @return
   */
  public static Node getChild(Node parent, int type) {
      Node n = parent.getFirstChild();
      while (n != null && type != n.getNodeType()) {
          n = n.getNextSibling();
      }
      if (n == null) {
          return null;
      }
      return n;
  }

}





Get the specified text node associated with this element

  
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Utils {
  /**
   * Get the first text node associated with this element
   * @param parent the node containing text
   * @return Text (trimmed of leanding/trailing whitespace, null if none)
   */
  public static String getFirstText(Node parent) {
    return getTextNodeByNumber(parent, 1);
  }
  /**
   * Get the specified text node associated with this element
   * @param parent the node containing text
   * @param number The text node to fetch (1st, 2nd, etc)
   * @return Text (trimmed of leanding/trailing whitespace, null if none)
   */
  public static String getTextNodeByNumber(Node parent, int number) {
    String  text  = null;
    int     count = 1;
    if (parent != null) {
      for (Node child = parent.getFirstChild();
                child != null;
                child = child.getNextSibling()) {
        if ((child.getNodeType() == Node.TEXT_NODE) && (count++ == number)) {
          text = child.getNodeValue();
          return text.trim();
        }
      }
    }
    return text;
  }
}





Get the trimed text content of a node or null if there is no text

  
import org.w3c.dom.Node;
/**
 *  
 *
 * @author Costin Manolache
 */
public class Main {

  /** Get the trimed text content of a node or null if there is no text
   */
  public static String getContent(Node n ) {
      if( n==null ) return null;
      Node n1=getChild(n, Node.TEXT_NODE);
      if( n1==null ) return null;
      String s1=n1.getNodeValue();
      return s1.trim();
  }
  /** Get the first direct child with a given type
   */
  public static Node getChild( Node parent, int type ) {
      Node n=parent.getFirstChild();
      while( n!=null && type != n.getNodeType() ) {
          n=n.getNextSibling();
      }
      if( n==null ) return null;
      return n;
  }
}





Get trimmed text content of a node or null if there is no text

  
import org.w3c.dom.Node;
public class Utils {
  /**
   * Get the trimmed text content of a node or null if there is no text
   */
  public static String getContent(Node n) {
      if (n == null) {
          return null;
      }
      Node n1 = getChild(n, Node.TEXT_NODE);
      if (n1 == null) {
          return null;
      }
      return n1.getNodeValue().trim();
  }
  /**
   * Get the raw text content of a node or null if there is no text
   */
  public static String getRawContent(Node n) {
      if (n == null) {
          return null;
      }
      Node n1 = getChild(n, Node.TEXT_NODE);
      if (n1 == null) {
          return null;
      }
      return n1.getNodeValue();
  }
  /**
   * Get the first child of the specified type.
   * 
   * @param parent
   * @param type
   * @return
   */
  public static Node getChild(Node parent, int type) {
      Node n = parent.getFirstChild();
      while (n != null && type != n.getNodeType()) {
          n = n.getNextSibling();
      }
      if (n == null) {
          return null;
      }
      return n;
  }

}





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;
}
}





Import Elements

  
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed 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.
 ******************************************************************************/
/**
 * Various XML utilities.
 * 
 * @author simonjsmith, ksim
 * @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
 * @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
 *          manipulation
 */
public class Utils {
  public static void importElements(Document document, Element parent,
      Element[] children) {
    for (int i = 0; i < children.length; i++) {
      parent.appendChild(document.importNode(children[i], true));
    }
  }
}





Macro to get the content of a unique child element.

  
import java.util.ArrayList;
import java.util.Iterator;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
public class Utils {
  /**
   * Macro to get the content of a unique child element.
   *
   * @param element    The parent element.
   * @param tagName    The name of the desired child.
   * @return           The element content or null.
   */
  public static String getUniqueChildContent(Element element,
                                             String tagName)
     throws Exception
  {
     return getElementContent(getUniqueChild(element, tagName));
  }
  /**
   * Get the content of the given element.
   *
   * @param element    The element to get the content for.
   * @return           The content of the element or null.
   */
  public static String getElementContent(final Element element)
     throws Exception
  {
     return getElementContent(element, null);
  }
  /**
   * Get the content of the given element.
   *
   * @param element       The element to get the content for.
   * @param defaultStr    The default to return when there is no content.
   * @return              The content of the element or the default.
   */
  public static String getElementContent(Element element, String defaultStr)
     throws Exception
  {
     if (element == null)
        return defaultStr;
     NodeList children = element.getChildNodes();
     String result = "";
     for (int i = 0; i < children.getLength(); i++)
     {
        if (children.item(i).getNodeType() == Node.TEXT_NODE || 
            children.item(i).getNodeType() == Node.CDATA_SECTION_NODE)
        {
           result += children.item(i).getNodeValue();
        }
        else if( children.item(i).getNodeType() == Node.ruMENT_NODE )
        {
           // Ignore comment nodes
        }
     }
     return result.trim();
  }
  /**
   * Gets the child of the specified element having the specified unique
   * name.  If there are more than one children elements with the same name
   * and exception is thrown.
   *
   * @param element    The parent element
   * @param tagName    The name of the desired child
   * @return           The named child.
   *
   * @throws Exception   Child was not found or was not unique.
   */
  public static Element getUniqueChild(Element element, String tagName)
     throws Exception
  {
     Iterator<Element> goodChildren = getChildrenByTagName(element, tagName);
     if (goodChildren != null && goodChildren.hasNext()) {
        Element child = goodChildren.next();
        if (goodChildren.hasNext()) {
           throw new Exception
              ("expected only one " + tagName + " tag");
        }
        return child;
     } else {
        throw new Exception
           ("expected one " + tagName + " tag");
     }
  }
  /**
   * Returns an iterator over the children of the given element with
   * the given tag name.
   *
   * @param element    The parent element
   * @param tagName    The name of the desired child
   * @return           An interator of children or null if element is null.
   */
  public static Iterator<Element> getChildrenByTagName(Element element,
                                              String tagName)
  {
     if (element == null) return null;
     // getElementsByTagName gives the corresponding elements in the whole 
     // descendance. We want only children
     NodeList children = element.getChildNodes();
     ArrayList<Element> goodChildren = new ArrayList<Element>();
     for (int i=0; i<children.getLength(); i++) {
        Node currentChild = children.item(i);
        if (currentChild.getNodeType() == Node.ELEMENT_NODE && 
            ((Element)currentChild).getTagName().equals(tagName)) {
           goodChildren.add((Element)currentChild);
        }
     }
     return goodChildren.iterator();
  }
}





Moves the content of the given element to the given element

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Utils {
  /**
   * 
   */
  public static void moveContent(Element from, Element to) {
      // lets move the child nodes across
      NodeList childNodes = from.getChildNodes();
      while (childNodes.getLength() > 0) {
          Node node = childNodes.item(0);
          from.removeChild(node);
          to.appendChild(node);
      }
  }
}





Remove Attribute

  
/**
 * 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 javax.xml.namespace.QName;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
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 {
  public static void removeAttribute(Node node, String attName) {
    NamedNodeMap attributes = node.getAttributes();
    attributes.removeNamedItem(attName);
  }
}





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() == 0) ? null : (Element) nodeList.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((Element) elementList.item(i), attribute).equals(value)) {
        resultList.add(elementList.item(i));
        if (returnFirst) {
          break;
        }
      }
    }
    return resultList;
  }
}





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 (n instanceof Element) {
        Element e = (Element) n;
        String eNs = (e.getNamespaceURI() == null) ? "" : e.getNamespaceURI();
        if (ns.equals(eNs) && localName.equals(e.getLocalName())) {
          r.add(e);
        }
      }
    }
    return r;
  }
}





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 = (Element) node;
              if(element.getTagName().equals(name)) {
                  elements.add(element);
              }
          }
      }
      return elements;
  }
}





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 = (Node) children.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 = (Text) node;
                  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 = (Element) node;
              if(element.getTagName().equals(name)) {
                  elements.add(element);
              }
          }
      }
      return elements;
  }
}





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 = (Text) node;
              buf.append(text.getData().trim());
          }
      }
      return buf.toString();
  }

}





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 = (Element) node;
              if(element.getTagName().equals(name)) {
                  return element;
              }
          }
      }
      return null;
  }
}





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) {
    for( Node 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 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();
  }
}





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() == 0) ? null : (Element) nodeList.item(0);
  }
}





Use the Document.getElementsByTagName() method to quickly and easily locate elements by 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.io.PrintWriter;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
/**
 * A sample DOM filter. This sample program illustrates how to
 * use the Document#getElementsByTagName() method to quickly
 * and easily locate elements by name.
 *
 * @author Jeffrey Rodriguez, IBM
 * @author Andy Clark, IBM
 *
 * @version $Id: GetElementsByTagName.java 447683 2006-09-19 02:36:31Z mrglavas $
 */
public class GetElementsByTagName {
    //
    // Constants
    //
    // feature ids
    /** Namespaces feature id (http://xml.org/sax/features/namespaces). */
    protected static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";
    /** Validation feature id (http://xml.org/sax/features/validation). */
    protected static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";
    /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */
    protected static final String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";
    /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */
    protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
    
    /** Honour all schema locations feature id (http://apache.org/xml/features/honour-all-schemaLocations). */
    protected static final String HONOUR_ALL_SCHEMA_LOCATIONS_ID = "http://apache.org/xml/features/honour-all-schemaLocations";
    
    /** Validate schema annotations feature id (http://apache.org/xml/features/validate-annotations). */
    protected static final String VALIDATE_ANNOTATIONS_ID = "http://apache.org/xml/features/validate-annotations";
    
    /** Dynamic validation feature id (http://apache.org/xml/features/validation/dynamic). */
    protected static final String DYNAMIC_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/dynamic";
    
    /** XInclude feature id (http://apache.org/xml/features/xinclude). */
    protected static final String XINCLUDE_FEATURE_ID = "http://apache.org/xml/features/xinclude";
    
    /** XInclude fixup base URIs feature id (http://apache.org/xml/features/xinclude/fixup-base-uris). */
    protected static final String XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID = "http://apache.org/xml/features/xinclude/fixup-base-uris";
    
    /** XInclude fixup language feature id (http://apache.org/xml/features/xinclude/fixup-language). */
    protected static final String XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID = "http://apache.org/xml/features/xinclude/fixup-language";
    // default settings
    /** Default parser name (dom.wrappers.Xerces). */
    protected static final String DEFAULT_PARSER_NAME = "dom.wrappers.Xerces";
    /** Default element name (*). */
    protected static final String DEFAULT_ELEMENT_NAME = "*";
    /** Default namespaces support (true). */
    protected static final boolean DEFAULT_NAMESPACES = true;
    /** Default validation support (false). */
    protected static final boolean DEFAULT_VALIDATION = false;
    /** Default Schema validation support (false). */
    protected static final boolean DEFAULT_SCHEMA_VALIDATION = false;
    /** Default Schema full checking support (false). */
    protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false;
    
    /** Default honour all schema locations (false). */
    protected static final boolean DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS = false;
    
    /** Default validate schema annotations (false). */
    protected static final boolean DEFAULT_VALIDATE_ANNOTATIONS = false;
    
    /** Default dynamic validation support (false). */
    protected static final boolean DEFAULT_DYNAMIC_VALIDATION = false;
    
    /** Default XInclude processing support (false). */
    protected static final boolean DEFAULT_XINCLUDE = false;
    
    /** Default XInclude fixup base URIs support (true). */
    protected static final boolean DEFAULT_XINCLUDE_FIXUP_BASE_URIS = true;
    
    /** Default XInclude fixup language support (true). */
    protected static final boolean DEFAULT_XINCLUDE_FIXUP_LANGUAGE = true;
    //
    // Public static methods
    //
    /** Prints the specified elements in the given document. */
    public static void print(PrintWriter out, Document document,
                             String elementName, String attributeName) {
        // get elements that match
        NodeList elements = document.getElementsByTagName(elementName);
        // is there anything to do?
        if (elements == null) {
            return;
        }
        // print all elements
        if (attributeName == null) {
            int elementCount = elements.getLength();
            for (int i = 0; i < elementCount; i++) {
                Element element = (Element)elements.item(i);
                print(out, element, element.getAttributes());
            }
        }
        // print elements with given attribute name
        else {
            int elementCount = elements.getLength();
            for (int i = 0; i < elementCount; i++) {
                Element      element    = (Element)elements.item(i);
                NamedNodeMap attributes = element.getAttributes();
                if (attributes.getNamedItem(attributeName) != null) {
                    print(out, element, attributes);
                }
            }
        }
    } // print(PrintWriter,Document,String,String)
    //
    // Protected static methods
    //
    /** Prints the specified element. */
    protected static void print(PrintWriter out,
                                Element element, NamedNodeMap attributes) {
        out.print("<");
        out.print(element.getNodeName());
        if (attributes != null) {
            int attributeCount = attributes.getLength();
            for (int i = 0; i < attributeCount; i++) {
                Attr attribute = (Attr)attributes.item(i);
                out.print(" ");
                out.print(attribute.getNodeName());
                out.print("=\"");
                out.print(normalize(attribute.getNodeValue()));
                out.print(""");
            }
        }
        out.println(">");
        out.flush();
    } // print(PrintWriter,Element,NamedNodeMap)
    /** Normalizes the given string. */
    protected static String normalize(String s) {
        StringBuffer str = new StringBuffer();
        int len = (s != null) ? s.length() : 0;
        for (int i = 0; i < len; i++) {
            char ch = s.charAt(i);
            switch (ch) {
            case "<": {
                    str.append("&lt;");
                    break;
                }
            case ">": {
                    str.append("&gt;");
                    break;
                }
            case "&": {
                    str.append("&amp;");
                    break;
                }
            case """: {
                    str.append("&quot;");
                    break;
                }
            case "\r":
            case "\n": {
                    str.append("&#");
                    str.append(Integer.toString(ch));
                    str.append(";");
                    break;
                }
            default: {
                    str.append(ch);
                }
            }
        }
        return str.toString();
    } // normalize(String):String
    //
    // MAIN
    //
    /** Main program entry point. */
    public static void main(String argv[]) {
        // is there anything to do?
        if (argv.length == 0) {
            printUsage();
            System.exit(1);
        }
        // variables
        PrintWriter out = new PrintWriter(System.out);
        ParserWrapper parser = null;
        String elementName = DEFAULT_ELEMENT_NAME;
        String attributeName = null;
        boolean namespaces = DEFAULT_NAMESPACES;
        boolean validation = DEFAULT_VALIDATION;
        boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
        boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
        boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
        boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
        boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
        boolean xincludeProcessing = DEFAULT_XINCLUDE;
        boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
        boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;
        // process arguments
        for (int i = 0; i < argv.length; i++) {
            String arg = argv[i];
            if (arg.startsWith("-")) {
                String option = arg.substring(1);
                if (option.equals("p")) {
                    // get parser name
                    if (++i == argv.length) {
                        System.err.println("error: Missing argument to -p option.");
                    }
                    String parserName = argv[i];
                    // create parser
                    try {
                        parser = (ParserWrapper)Class.forName(parserName).newInstance();
                    }
                    catch (Exception e) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser ("+parserName+")");
                    }
                    continue;
                }
                if (option.equals("e")) {
                    if (++i == argv.length) {
                        System.err.println("error: Missing argument to -e option.");
                    }
                    elementName = argv[i];
                    continue;
                }
                if (option.equals("a")) {
                    if (++i == argv.length) {
                        System.err.println("error: Missing argument to -a option.");
                    }
                    attributeName = argv[i];
                    continue;
                }
                if (option.equalsIgnoreCase("n")) {
                    namespaces = option.equals("n");
                    continue;
                }
                if (option.equalsIgnoreCase("v")) {
                    validation = option.equals("v");
                    continue;
                }
                if (option.equalsIgnoreCase("s")) {
                    schemaValidation = option.equals("s");
                    continue;
                }
                if (option.equalsIgnoreCase("f")) {
                    schemaFullChecking = option.equals("f");
                    continue;
                }
                if (option.equalsIgnoreCase("hs")) {
                    honourAllSchemaLocations = option.equals("hs");
                    continue;
                }
                if (option.equalsIgnoreCase("va")) {
                    validateAnnotations = option.equals("va");
                    continue;
                }
                if (option.equalsIgnoreCase("dv")) {
                    dynamicValidation = option.equals("dv");
                    continue;
                }
                if (option.equalsIgnoreCase("xi")) {
                    xincludeProcessing = option.equals("xi");
                    continue;
                }
                if (option.equalsIgnoreCase("xb")) {
                    xincludeFixupBaseURIs = option.equals("xb");
                    continue;
                }
                if (option.equalsIgnoreCase("xl")) {
                    xincludeFixupLanguage = option.equals("xl");
                    continue;
                }
                if (option.equals("h")) {
                    printUsage();
                    continue;
                }
            }
            // use default parser?
            if (parser == null) {
                // create parser
                try {
                    parser = (ParserWrapper)Class.forName(DEFAULT_PARSER_NAME).newInstance();
                }
                catch (Exception e) {
                    System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")");
                    continue;
                }
            }
            // set parser features
            try {
                parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
            }
            catch (SAXException e) {
                System.err.println("warning: Parser does not support feature ("+NAMESPACES_FEATURE_ID+")");
            }
            try {
                parser.setFeature(VALIDATION_FEATURE_ID, validation);
            }
            catch (SAXException e) {
                System.err.println("warning: Parser does not support feature ("+VALIDATION_FEATURE_ID+")");
            }
            try {
                parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
            }
            catch (SAXException e) {
                System.err.println("warning: Parser does not support feature ("+SCHEMA_VALIDATION_FEATURE_ID+")");
            }
            try {
                parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
            }
            catch (SAXException e) {
                System.err.println("warning: Parser does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
            }
            try {
                parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
            }
            catch (SAXException e) {
                System.err.println("warning: Parser does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")");
            }
            try {
                parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
            }
            catch (SAXException e) {
                System.err.println("warning: Parser does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
            }
            try {
                parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
            }
            catch (SAXException e) {
                System.err.println("warning: Parser does not support feature ("+DYNAMIC_VALIDATION_FEATURE_ID+")");
            }
            try {
                parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
            }
            catch (SAXException e) {
                System.err.println("warning: Parser does not support feature ("+XINCLUDE_FEATURE_ID+")");
            }
            try {
                parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
            }
            catch (SAXException e) {
                System.err.println("warning: Parser does not support feature ("+XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID+")");
            }
            try {
                parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
            }
            catch (SAXException e) {
                System.err.println("warning: Parser does not support feature ("+XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID+")");
            }
            // parse file
            try {
                Document document = parser.parse(arg);
                GetElementsByTagName.print(out, document, elementName, attributeName);
            }
            catch (SAXParseException e) {
                // ignore
            }
            catch (Exception e) {
                System.err.println("error: Parse error occurred - "+e.getMessage());
                if (e instanceof SAXException) {
                    Exception nested = ((SAXException)e).getException();
                    if (nested != null) {
                        e = nested;
                    }
                }
                e.printStackTrace(System.err);
            }
        }
    } // main(String[])
    //
    // Private static methods
    //
    /** Prints the usage. */
    private static void printUsage() {
        System.err.println("usage: java dom.GetElementsByTagName (options) uri ...");
        System.err.println();
        System.err.println("options:");
        System.err.println("  -p name     Select parser by name.");
        System.err.println("  -e name     Specify element name for search.");
        System.err.println("  -a name     Specify attribute name for specified elements.");
        System.err.println("  -n | -N     Turn on/off namespace processing.");
        System.err.println("  -v | -V     Turn on/off validation.");
        System.err.println("  -s | -S     Turn on/off Schema validation support.");
        System.err.println("              NOTE: Not supported by all parsers.");
        System.err.println("  -f  | -F    Turn on/off Schema full checking.");
        System.err.println("              NOTE: Requires use of -s and not supported by all parsers.");
        System.err.println("  -hs | -HS   Turn on/off honouring of all schema locations.");
        System.err.println("              NOTE: Requires use of -s and not supported by all parsers.");
        System.err.println("  -va | -VA   Turn on/off validation of schema annotations.");
        System.err.println("              NOTE: Requires use of -s and not supported by all parsers.");
        System.err.println("  -dv | -DV   Turn on/off dynamic validation.");
        System.err.println("              NOTE: Not supported by all parsers.");
        System.err.println("  -xi | -XI   Turn on/off XInclude processing.");
        System.err.println("              NOTE: Not supported by all parsers.");
        System.err.println("  -xb | -XB   Turn on/off base URI fixup during XInclude processing.");
        System.err.println("              NOTE: Requires use of -xi and not supported by all parsers.");
        System.err.println("  -xl | -XL   Turn on/off language fixup during XInclude processing.");
        System.err.println("              NOTE: Requires use of -xi and not supported by all parsers.");
        System.err.println("  -h          This help screen.");
        System.err.println();
        System.err.println("defaults:");
        System.err.println("  Parser:     "+DEFAULT_PARSER_NAME);
        System.err.println("  Element:    "+DEFAULT_ELEMENT_NAME);
        System.err.print("  Namespaces: ");
        System.err.println(DEFAULT_NAMESPACES ? "on" : "off");
        System.err.print("  Validation: ");
        System.err.println(DEFAULT_VALIDATION ? "on" : "off");
        System.err.print("  Schema:     ");
        System.err.println(DEFAULT_SCHEMA_VALIDATION ? "on" : "off");
        System.err.print("  Schema full checking:            ");
        System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off");
        System.err.print("  Honour all schema locations:     ");
        System.err.println(DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS ? "on" : "off");
        System.err.print("  Validate annotations:            ");
        System.err.println(DEFAULT_VALIDATE_ANNOTATIONS ? "on" : "off");
        System.err.print("  Dynamic:    ");
        System.err.println(DEFAULT_DYNAMIC_VALIDATION ? "on" : "off");
        System.err.print("  XInclude:   ");
        System.err.println(DEFAULT_XINCLUDE ? "on" : "off");
        System.err.print("  XInclude base URI fixup:  ");
        System.err.println(DEFAULT_XINCLUDE_FIXUP_BASE_URIS ? "on" : "off");
        System.err.print("  XInclude language fixup:  ");
        System.err.println(DEFAULT_XINCLUDE_FIXUP_LANGUAGE ? "on" : "off");
    } // printUsage()
} // class GetElementsByTagName

/**
 * Encapsulates a DOM parser.
 *
 * @version $Id: ParserWrapper.java 447683 2006-09-19 02:36:31Z mrglavas $
 */
 interface ParserWrapper {
    //
    // ParserWrapper methods
    //
    /** Parses the specified URI and returns the document. */
    public Document parse(String uri) throws Exception;
    /**
     * Set the state of a feature.
     *
     * Set the state of any feature in a SAX2 parser.  The parser
     * might not recognize the feature, and if it does recognize
     * it, it might not be able to fulfill the request.
     *
     * @param featureId The unique identifier (URI) of the feature.
     * @param state The requested state of the feature (true or false).
     *
     * @exception org.xml.sax.SAXNotRecognizedException If the
     *            requested feature is not known.
     * @exception org.xml.sax.SAXNotSupportedException If the
     *            requested feature is known, but the requested
     *            state is not supported.
     * @exception org.xml.sax.SAXException If there is any other
     *            problem fulfilling the request.
     */
    public void setFeature(String featureId, boolean state)
        throws  SAXNotRecognizedException, SAXNotSupportedException; 
    /** Returns the document information. */
    public DocumentInfo getDocumentInfo();
    //
    // Interfaces
    //
    /**
     * This interface is here to query information about the document
     * implementation returned by the <code>ParserWrapper#parse</code>
     * method.
     *
     * @author Andy Clark, IBM
     */
    public interface DocumentInfo {
        //
        // DocumentInfo methods
        //
        /** 
         * Returns true if the specified text node is ignorable whitespace. 
         */
        public boolean isIgnorableWhitespace(Text text);
    } // interface DocumentInfo
} // interface ParserWrapper