XML之JDOM解析

来源:互联网 发布:英制螺丝孔算法 编辑:程序博客网 时间:2024/06/05 00:18

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对象,格式化xmlFormat 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();}}}


0 0
原创粉丝点击