package com.bocloud.cmp.model.h3c.utils;

import java.io.StringWriter;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.transform.OutputKeys;
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.Document;
import org.w3c.dom.Element;

public class ElementUtils {
	/**
	 * 转换给xml
	 *
	 * @param element
	 * @return
	 * @throws Exception
	 */
	public static String toFormatedXML(Element element) throws Exception {
		TransformerFactory transFactory = TransformerFactory.newInstance();
		transFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
		Transformer transFormer = transFactory.newTransformer();
		transFormer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		DOMSource domSource = new DOMSource(element);
		StringWriter sw = new StringWriter();
		StreamResult xmlResult = new StreamResult(sw);
		transFormer.transform(domSource, xmlResult);
		return sw.toString();
	}

	/**
	 * 增加子节点
	 *
	 * @param parent
	 * @param tag
	 * @param value
	 * @return
	 */
	public static Element addChild(Element parent, String tag, Object value) {
		Element child = parent.getOwnerDocument().createElement(tag);
		if (null != value) {
			child.setTextContent(value.toString());
		}
		parent.appendChild(child);
		return child;
	}

	/**
	 * 创建根节点
	 *
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public static Element creatRoot(String name) throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// disable external entities
		factory.setAttribute(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
		factory.setAttribute(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.newDocument();
		Element root = document.createElement(name);
		return root;
	}
}
