生成XML
16lz
2021-01-26
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");//添加子元素到lan1lan1.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");//添加子元素到lan1lan2.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");//添加子元素到lan1lan3.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();}
更多相关文章
- Android中Fragment通过接口回调传递数据到Activity中
- android 实现Listview 动态删除
- 使用Toast显示提示信息框
- 安装时提示:INSTALL_FAILED_INSUFFICIENT_STORAGE
- Android(安卓)代码监控apk安装,卸载,替换
- Android打包常见问题的解决办法
- 使用SmartRefreshLayout 给RecyclerView 添加反弹效果示例
- android笔记4-xml解析
- view.java