生成XML

try
{
DocumentBuilderFactory docbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docbuilder = docbf.newDocumentBuilder();
Document newxml = docbuilder.newDocument();
//创建根元素
Element language = newxml.createElement("Languages");
//设定属性
language.setAttribute("cat","it");

//创建父元素
Element lan1 = newxml.createElement("lan");
lan1.setAttribute("id","1");
//创建子元素
Element name1 = newxml.createElement("name");
name1.setTextContent("Java");
Element ide1 = newxml.createElement("ide");
ide1.setTextContent("Eclipse");
//添加子元素到lan1
lan1.appendChild(name1);
lan1.appendChild(ide1);

//创建父元素
Element lan2 = newxml.createElement("lan");
lan1.setAttribute("id","2");
//创建子元素
Element name2 = newxml.createElement("name");
name1.setTextContent("Swift");
Element ide2 = newxml.createElement("ide");
ide1.setTextContent("Xcode");
//添加子元素到lan1
lan2.appendChild(name2);
lan2.appendChild(ide2);

//创建父元素
Element lan3 = newxml.createElement("lan");
lan1.setAttribute("id","3");
//创建子元素
Element name3 = newxml.createElement("name");
name1.setTextContent("C#");
Element ide3 = newxml.createElement("ide");
ide1.setTextContent("Visual Studio");
//添加子元素到lan1
lan3.appendChild(name3);
lan3.appendChild(ide3);

//将lan添加到根元素
language.appendChild(lan1);
language.appendChild(lan2);
language.appendChild(lan3);

//将根元素添加到文档
newxml.appendChild(language);

TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
tf.setOutputProperty("encoding","utf-8");
StringWriter sw = new StringWriter();
tf.transform(new DOMSource(newxml),new StreamResult(sw));
tv.setText(sw.toString());


} catch (ParserConfigurationException e)
{
e.printStackTrace();
} catch (TransformerConfigurationException e)
{
e.printStackTrace();
} catch (TransformerException e)
{
e.printStackTrace();
}

相关文章

引言 NOKIA 有句著名的广告语:“科技以人为本”。任何技术都是为了满足人的生产生活需要而产生的。具体...
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Reprint it anywhere u want. 文章...
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Reprint it anywhere u want. 文章...
http://blog.jobbole.com/79252/ 引言 NOKIA 有句著名的广告语:“科技以人为本”。任何技术都是为了满...
(点击上方公众号,可快速关注) 公众号:smart_android 作者:耿广龙|loonggg 点击“阅读原文”,可查看...
一、xml与xslt 相信所有人对xml都不陌生,其被广泛的应用于数据数据传输、保存与序列化中,是一种极为强...