前端之家收集整理的这篇文章主要介绍了
生成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();
}