/**
 * Copyright 2008-2009 DRIVER PROJECT (Bielefeld University)
 * Original author: Marek Imialek <marek.imialek at uni-bielefeld.de>
 *
 * 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.
 */
package eu.dnetlib.data.sts.profile.utils;

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

/**
 * @author <a href="mailto:marek.imialek at uni-bielefeld.de">Marek Imialek</a>
 *
 */
public class Marshaller {

	/**
	 * Gets the single element.
	 * 
	 * @param root the root
	 * @param elementName the element name
	 * 
	 * @return the single element
	 */
	public static Element getSingleElement(Element root, String elementName) {
		if (root == null || elementName == null)
			return null;
		NodeList nodeList = root.getElementsByTagName(elementName);
		if (nodeList == null || nodeList.getLength() == 0)
			return null;
		return (Element) nodeList.item(0);
	}

	/**
	 * Gets the single element value attr.
	 * 
	 * @param root the root
	 * @param elementName the element name
	 * 
	 * @return the single element value attr
	 */
	public static String getSingleElementValueAttr(Element root,
			String elementName) {
		Element el = getSingleElement(root, elementName);
		if (el != null)
			return el.getAttribute("value");
		else
			return null;
	}

	/**
	 * Gets the single element attribute.
	 * 
	 * @param root the root
	 * @param elementName the element name
	 * @param attrName the attr name
	 * 
	 * @return the single element attribute
	 */
	public static String getSingleElementAttribute(Element root,
			String elementName, String attrName) {
		if (attrName == null)
			return null;
		Element el = getSingleElement(root, elementName);
		if (el != null)
			return el.getAttribute(attrName);
		else
			return null;
	}

	/**getSingleElementValueAttr
	 * Gets the element content.
	 * 
	 * @param element the element
	 * 
	 * @return the element content
	 */
	public static String getElementContent(Element element) {
		if (element == null)
			return null;
		if (element.getFirstChild() != null)
			return element.getFirstChild().getTextContent();
		else
			return null;

	}

}
