`

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);			} 
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics