1.什么是JDOM?
JDOM(Java-based Document Object Model)
Java特定的文档对象模型。自身不包含解析器,使用SAX。
优点:
1、使用具体类而不是接口,简化了DOM的API。
2、大量使用了Java集合类,方便了Java开发人员。
缺点:
1、没有较好的灵活性。
2、性能较差。
2.代码示例
/** *jdom方法生成xml文件 */ public static void jdomCreateXml(){ //创建根节点 Element root = new Element("Location"); //创建document对象 Document document = new Document(root); //添加子节点 Element child = new Element("CountryRegion"); child.setAttribute("Name","中国"); child.setAttribute("Code","1"); //添加子节点 Element subchild = new Element("State"); subchild.setAttribute("Name","四川"); subchild.setAttribute("Code","sc"); //添加子节点 Element subsubchild = new Element("City"); subsubchild.setAttribute("Name","成都"); subsubchild.setAttribute("Code","cd"); //添加孙子节点 subchild.addContent(subsubchild); //添加子节点 child.addContent(subchild); //添加节点 root.addContent(child); //创建Format对象,格式化xml Format formater =Format.getPrettyFormat(); //创建XMLOutputter对象 XMLOutputter outputer = new XMLOutputter(formater); //初始化输出流,局部变量必须初始化 OutputStream out = null; //创建XML文件 File file = new File("LocListJdom.xml"); try { if (!file.exists()){ if (!file.createNewFile()){ throw new FileCanNotCreateException(); } } //创建输出流 out = new FileOutputStream(file); //XMLOutputter写入 outputer.output(document,out); } catch (IOException e) { e.printstacktrace(); e.printstacktrace(); } catch (FileCanNotCreateException e) { e.printstacktrace(); } finally{ //关闭流 try { out.close(); } catch (IOException e) { e.printstacktrace(); } } }
原文地址:https://www.jb51.cc/xml/294289.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。