XML之DOM4J解析

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

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念