/**
 * $Id: XmlUtils.java,v 1.1 2004/08/23 10:54:21 bigmac Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 */

package vkc.xml;

import java.io.IOException;
import java.io.StringWriter;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Collection of some usefull XML processing methods
 */
public class XmlUtils {

	/**
	 * Method converts the input xml document into a string representation
	 */
	public final static String convertToString( Document xmlDoc ) 
	throws IOException {

		if ( xmlDoc==null ) {
			return null;
		}

		OutputFormat format = new OutputFormat( xmlDoc );
		format.setMethod( "xml" );
		format.setLineWidth( 80 );
		format.setIndenting( true );
		format.setIndent( 2 );

		StringWriter sw = new StringWriter();

		XMLSerializer serializer = new XMLSerializer( sw, format );
		serializer.serialize( xmlDoc );

		return sw.toString();
	}
	
	/**
	 * Mehod returns the first Node matching the given name
	 * <p>
	 * @param nodes - NodeList
	 * @return Node matching the given node name
	 */
	public final static Node getNodeByName( Node node, String name ) {

		if ( node==null || name==null) {
			return null;
		}

		if ( node.getNodeName().equals( name ) ) {
			return node;
		}

		NodeList nodes = node.getChildNodes();
		
		for ( int i=0 ; nodes!=null && i < nodes.getLength() ; i++ ) {

			Node child = nodes.item( i );
			Node foundNode = getNodeByName( child, name );
			if ( foundNode!=null ) {
				return foundNode;
			}
		}
		return null;
	}	
}
