加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML之DOM4J解析

发布时间:2020-12-16 02:06:02 所属栏目:百科 来源:网络整理
导读:1.什么是JDOM? JDOM(Java-based Document Object Model) Java特定的文档对象模型。自身不包含解析器,使用SAX。 优点: 1、使用具体类而不是接口,简化了DOM的API。 2、大量使用了Java集合类,方便了Java开发人员。 缺点: 1、没有较好的灵活性。 2、性能

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();
			}
		}
		
	}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读