java 生成xml格式的文件

来源:互联网 发布:如何解绑支付宝和淘宝 编辑:程序博客网 时间:2024/04/29 17:43

在开发中,我们需要记录一些信息,比如我在写android应用时 ,喜欢将手机设备信息以xml格式包装,然后邮件形式发送到我的邮箱里。这样有利于调试crash信息

下面介绍怎么用java生成xml格式的文件

首先你需要jdom.jar和dom4j.jar这两个包

/** * 将crash信息打包成xml格式 * @param hashMap 原始crash信息的hashmap形式 * @throws IOException * @throws JDOMException */public void BuildXMLDoc(HashMap<String, String> hashMap) throws IOException, JDOMException {int size = hashMap.size();Iterator iter = hashMap.entrySet().iterator();Map.Entry entry;String key;String val;int id = 1;// 创建根节点 list;Element root = new Element("phoneInfo");// 根节点添加到文档中;Document Doc = new Document(root);// 此处 迭代器的遍历 可替换成循环遍历 数据库表的结果集操作;while (iter.hasNext()) {entry = (Map.Entry)iter.next();key = (String)entry.getKey();val = hashMap.get(key);if (val == null || val.length() == 0){val = "null";}// 创建节点 user;Element elements = new Element("category");// 给 user 节点添加属性 id;elements.setAttribute("id", "" + id);id ++;// 给 user 节点添加子节点并赋值;// new Element("name")中的 "name" 替换成表中相应字段,setText("xuehui")中 "xuehui// 替换成表中记录值;elements.addContent(new Element(key).setText(val));// 给父节点list添加user子节点;root.addContent(elements);}//带有缩进格式的xml 更美观Format format = Format.getPrettyFormat();XMLOutputter XMLOut = new XMLOutputter(format);XMLOut.output(Doc, new FileOutputStream(FileUtil.CRASHPATH));System.out.println("完成了文件写入");}

上面虽然是对hashmap的遍历,但是对于其他容器的遍历形式不变,只是换成你需要的信息即可

下面是其他文章找到的

生成XML的时候,处理特殊字符

element.addContent(new CDATA("<xml> content"));

生成XML的时候,设置编码

XMLOutputter XMLOut = new XMLOutputter();XMLOut.setEncoding("gb2312");XMLOut.output(Doc, new FileOutputStream("test1.xml"));





0 0