栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 人工智能 > NLP

android dom方式创建xml

NLP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

android dom方式创建xml

android dom 解析xml方式文章中,简单介绍了dom解析xml的应用。今天在原文章的基础上,说一下android中dom创建xml的应用。

首先:创建的文件会放在/data/data/cn.com.xxx(当前包名)/files下面。

创建生成的xml文件如下所示:

语文90英语80

可以直接用android dom 解析xml方式文章中方法去解析,注意修改一点:


// 从assets文件夹下获取文件 转换成输入流//inStream = this.getResources().getAssets().open(fileName);//doc = docBuilder.parse(inStream);InputStream fosStream = openFileInput(fileName);doc = docBuilder.parse(fosStream);

同时,fileName取得方法:


String[] fileNames = getFilesDir().list();
String fileName = fileNames[0];

解析出来的结果是



以下是创建xml文件的代码:

private void createXmlFile(){try {documentBuilderFactory factory = documentBuilderFactory.newInstance();documentBuilder builder = factory.newdocumentBuilder();document doc  = builder.newdocument();//创建xml根元素Element rootEle = doc.createElement("classes");doc.appendChild(rootEle);//创建xml二级元素Element groupEle = doc.createElement("group");groupEle.setAttribute("name", "一年级");groupEle.setAttribute("num", "10");//创建xml person元素Element personEle = doc.createElement("person");//personEle 的属性和属性值personEle.setAttribute("name", "小明");personEle.setAttribute("age", "7");//创建personELe的子元素Element chinese = doc.createElement("chinese");//创建personELe的子元素的值chinese.appendChild(doc.createTextNode("语文90"));personEle.appendChild(chinese);Element english = doc.createElement("english");english.appendChild(doc.createTextNode("英语80"));personEle.appendChild(english);groupEle.appendChild(personEle);rootEle.appendChild(groupEle);TransformerFactory tf = TransformerFactory.newInstance();Transformer transformer = tf.newTransformer();DOMSource source = new DOMSource(doc);transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");transformer.setOutputProperty(OutputKeys.INDENT, "no");//创建文件存放在 /data/data/cn.xxx.xxx(当前包)/files FileOutputStream fos = openFileOutput("Dom.xml", Context.MODE_PRIVATE);//创建文件存放在 /data/data/cn.xxx.xxx(当前包)/cache//FileOutputStream fos = OpPrintWriter pw = new PrintWriter(fos);StreamResult result = new StreamResult(pw);transformer.transform(source, result);System.out.println("生成XML文件成功!");} catch (ParserConfigurationException e) {System.out.println(e.getMessage());} catch (TransformerConfigurationException e) {System.out.println(e.getMessage());} catch (TransformerException e) {System.out.println(e.getMessage());} catch (FileNotFoundException e) {System.out.println(e.getMessage());}}

以上就是android dom方式创建xml的内容,更多相关内容请关注PHP中文网(www.kaotop.com)!


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/794877.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号