dom4j的简单应用

  在做一个进销存项目,底层存储结构由原先的Mysql改为了直接用xml来存,所以特意去学了一下dom4j的一些使用方法。
  可能一些例子会借用网上已流传开来的代码,毕竟挺适合入门的。
  先贴代码吧。
 /**
     *
     * @param filename
     * @return:return o stand for sucessfully! return 1 stand for fail!
     * @throws IOException 
     */
    public int createXmlFile(String filename) throws IOException{
    	int returnValue = 0;
    	//取得document对象,也就是XML文档对象
    	Document document = org.dom4j.DocumentHelper.createDocument();
    	//建立根结点
    	Element booksElement = document.addElement("books");
    	//加一行注解
    	booksElement.addComment("This is my Dom4J test firstly!!");
    	//建立第一个子结点
    	Element bookElement = booksElement.addElement("book");
    	//为子结点添加属性
    	bookElement.addAttribute("show", "yes");
    	//为子结点添加一个title标题
    	bookElement.addElement("title").setText("Lucene Studing");
    	
    	//建立第二个子结点
    	bookElement = booksElement.addElement("book");
    	//为子结点添加属性
    	bookElement.addAttribute("show", "yes");
    	//为子结点添加一个title标题
    	bookElement.addElement("title").setText("Dom4j  Tutorials");
    	
    	//建立第三个子结点
    	bookElement = booksElement.addElement("book");
    	//为子结点添加属性
    	bookElement.addAttribute("show", "yes");
    	//为子结点添加一个title标题
    	bookElement.addElement("title").setText("Lucene in Action");
    	
    	//建立第四个结点
    	Element owner = booksElement.addElement("owner");
    	owner.setText("O'Reilly");
    	File file = new File(filename);
    	FileWriter fw = new FileWriter(file);
    	OutputFormat format = OutputFormat.createPrettyPrint();
    	format.setEncoding("GBK");
    	org.dom4j.io.XMLWriter xmlWriter = new XMLWriter(fw,format);
    	xmlWriter.write(document);
    	xmlWriter.flush();
    	xmlWriter.close();
    	returnValue = 1;
		return returnValue;
    	
    }
    
    public int ModiXMLFile(String filename,String newfilename) throws IOException{
    	int resultvale = 0;
    	//取得document结象
    	try {
			SAXReader reader = new org.dom4j.io.SAXReader(filename);
			Document document = reader.read(new File(filename));
			//取得list
			List list = document.selectNodes("/books/book/@show");
			Iterator iter = list.iterator();
			while(iter.hasNext()){
				Attribute attribute = (Attribute)iter.next();
				if(attribute.getValue().equals("yes")){
					attribute.setValue("no");
				}
			}
			
			list = document.selectNodes("/books/owner");
			iter = list.iterator(); 
			if(iter.hasNext()){
				Element owner = (Element)iter.next();
				owner.setText("Tshinghua");
				Element dataElement = owner.addElement("data");
				dataElement.setText("2011-10-11");
				dataElement.addAttribute("type", "Gregorian calendar");
			}
			
			list = document.selectNodes("/books/book");
			iter = list.iterator();
			while(iter.hasNext()){
				Element bookElement = (Element)iter.next();
				Iterator iterator = bookElement.elementIterator("title");
				while(iterator.hasNext()){
					Element titleElement = (Element)iterator.next();
					if(titleElement.getText().equals("Dom4j Tutorials")){
						bookElement.remove(titleElement);
					}
				}
			}
			XMLWriter writer = new XMLWriter(new FileWriter(new File(newfilename)));
			writer.write(document);
			writer.close();
			return resultvale;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	return resultvale;
    }
    
    /**
     * 格式化XML 文档,并解决中文问题
     * @param filename
     * @return
     * @throws IOException 
     */
    public int formatXMLFile(String filename) throws IOException{
    	/** 返回操作结果, 0 表失败, 1 表成功*/
    	int returnValue = 0;
    	SAXReader reader = new SAXReader();
    	try {
			Document document = reader.read(new File(filename));
			XMLWriter writer = null;
			//得到格式化输出对像
			//紧凑型
			OutputFormat format = OutputFormat.createCompactFormat();
			//优雅型
			//OutputFormat format = OutputFormat.createPrettyPrint();
			//设定格式化的字符集,以支持中文 
			format.setEncoding("UTF-8");
			writer = new XMLWriter(new FileWriter(new File(filename)),format);
		    writer.write(document);
		    writer.close();
		    returnValue =1;
    	} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	return returnValue;
    }
    
    /**
     * 各种迭代法
     * @param document
     * @throws DocumentException
     */
    public void bar(Document document) throws DocumentException {
    	Element root = document.getRootElement();
    	//迭代根元素下面的所有子元素
    	for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
    	Element element = (Element) i.next();
    	//处理代码
    	}
    	//迭代根元素下面名称为"foo"的子元素
    	for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
    	Element foo = (Element) i.next();
    	//处理代码
    	}
    	// 迭代根元素的属性attributes)元素
    	for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
    	Attribute attribute = (Attribute) i.next();
    	// do something
    	}
    	}

   上面是网上的一些代码例子,我自已是理解了,然后重新敲了一遍。体会是dom4j在读写操作xml方面还是挺不错的,生成xml文件实际是一个建树的过程,一个node一个node的接上去,然后对每个node加上一些属性,数值。最终会建成一颗只有一个根结点的树。当建好树,你想写入到真正的文件中时,如有中文,可以格式化一下文档对像,有两种排列文式可以让你选技,当然,不同版本的DOM4J可能有不同的外插件实现更多的人性化功能,而我觉得本身它最终的开发版功能已经足够了。
    而对xml文件进行读取的时候,实际上是一个反向过程,它提供了XPATH等快速定位结点的功能,再结合一系列的迭代方法,相信你可以很快的找到你想要的结点,进而对它进行修改,删除等一系列操作。
    下面贴出我写的一个添加表单的方法,以供大家学习。
/**
	 * 添加新的进货单到xml中
	 * 
	 * @flag:1:为进货单 2:为出货单 3:为借卖单 4为借出单
	 * @return:如果操作成功返回1,否则反回0;
	 * @throws IOException
	 */
	public int AddStockList(Object obj) throws IOException {
		int resultvale = 0;
		Document document = null;
		try {
			SAXReader reader = new org.dom4j.io.SAXReader();
			document = reader.read(new File("rc/进货单.xml"));

			Element rootElement = document.getRootElement();

			Element saleListElement = rootElement.addElement("进货单号").addAttribute("进货单号", "")
					.addAttribute("日期", "").addAttribute("录入人", "")
					.addAttribute("经手人", "").addAttribute("供应商名称", "")
					.addAttribute("联系人", "").addAttribute("联系方式", "")
					.addAttribute("总金额", "").addAttribute("已付款", "");

			Element goodElement = saleListElement.addElement("进货项");
			Element publicElement = goodElement.addElement("货物名称");
			publicElement.setText("");
			publicElement = goodElement.addElement("批次");
			publicElement.setText("");
			publicElement = goodElement.addElement("规格");
			publicElement.setText("");
			publicElement = goodElement.addElement("描述");
			publicElement.setText("");
			publicElement = goodElement.addElement("单价");
			publicElement.setText("");
			publicElement = goodElement.addElement("数量");
			publicElement.setText("");
			Element entryElement = goodElement.addElement("已入库记录")
					.addAttribute("入库总数量", "");
			publicElement = entryElement.addElement("入库记录")
					.addAttribute("日期", "").addAttribute("数量", "");

			Element expenditureElement = saleListElement.addElement("出账记录");
			Element dataElement = expenditureElement.addElement("出账日期");
			dataElement.setText("");
			Element moneyElement = expenditureElement.addElement("出账金额");
			moneyElement.setText("");

			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("GBK");
			XMLWriter writer = new XMLWriter(new FileWriter(new File(
					"rc/进货单.xml")),format);
			writer.write(document);
			writer.close();
			return resultvale;
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return resultvale;
	}
	


/**
	 * 以清单号来查询数据
	 * @param number
	 * @return
	 */
	public Object SelectByNumber(String number){
		SAXReader reader = new org.dom4j.io.SAXReader();
		Document document;
		try {
			document = reader.read(new File("rc/借出单.xml"));
			Element rootElement = document.getRootElement();
			Iterator iter = rootElement.elementIterator();
			while(iter.hasNext()){
				Element infoElement = (Element)iter.next();
				if(infoElement.attributeValue("借卖单号").equals(number)){
					//取数据
				}
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 保存修改后的清单
	 * @param boj
	 */
	public void SaveGoodsList(Object obj,String number){
		SAXReader reader = new org.dom4j.io.SAXReader();
		Document document;
		try {
			document = reader.read(new File("rc/借卖单.xml"));
			Element rootElement = document.getRootElement();
			Iterator iter = rootElement.elementIterator();
			while(iter.hasNext()){
				Element infoElement = (Element)iter.next();
				if(infoElement.attributeValue("借卖单号").equals(number)){
					//移除该结点,利用add方法加入新结点
					document.remove(infoElement);
					AddMarginSellingList(obj);
				}
			}
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("GBK");
			XMLWriter writer = new XMLWriter(new FileWriter(new File(
					"rc/借卖单.xml")),format);
			writer.write(document);
			writer.close();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 以清单号来删除某一清单
	 * @param obj
	 * @param number
	 */
	public void DelGoodsList(String number){
		SAXReader reader = new org.dom4j.io.SAXReader();
		Document document;
		try {
			document = reader.read(new File("rc/借卖单.xml"));
			Element rootElement = document.getRootElement();
			Iterator iter = rootElement.elementIterator();
			while(iter.hasNext()){
				Element infoElement = (Element)iter.next();
				if(infoElement.attributeValue("借卖单号").equals(number)){
					//移除该结点,利用add方法加入新结点
					System.out.println(infoElement.getName());
					rootElement.remove(infoElement);
				}
			}
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("GBK");
			XMLWriter writer = new XMLWriter(new FileWriter(new File(
					"rc/借卖单.xml")),format);
			writer.write(document);
			writer.close();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

 

你可能感兴趣的:(dom4j)