天天看点

JAVA - DOM4J - XML 转化成String字串

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.tree.DefaultAttribute;
import org.dom4j.tree.DefaultElement;

Document document = DocumentHelper.createDocument();
Element root = document.addElement("response");  
Element lst = root.addElement("lst"); 
Element int1 = lst.addElement("int"); 
int1.addAttribute("name", "status");
int1.addText(status);
Element int2 = lst.addElement("int"); 
int2.addAttribute("name", "QTime");
int2.addText(QTime);
Element str1 = root.addElement("str"); 
str1.addAttribute("name", "core");
str1.addText(coreName);
Element str2 = root.addElement("str"); 
str2.addAttribute("name", "saved");
str2.addText(solrXmlPath);
		
// write XML
XMLWriter xmlWriter = null;
StringWriter out = new StringWriter(1024);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
try
{
	xmlWriter = new XMLWriter(out, format);
	xmlWriter.write(document); 
	ret = out.toString();;
}
catch (UnsupportedEncodingException ex)
{
	log.error("xml encoding error: " + ex);
}
catch (IOException ex)
{
        log.error("xml writing error: " + ex);
}
finally
{
    if (xmlWriter != null)
	{
		try
		{
			xmlWriter.close();
		}
		catch (IOException ex)
		{
			log.error("error occured when closing XMLWriter: " + ex);
		} 
	}
			
	if (out != null)
	{
		try
		{
			out.close();
		}
		catch (IOException ex)
		{
			log.error("error occured when closing StringWriter: " + ex);			} 
	}
}