dom4j读取xmL

xml格式如下:
<?xml version="1.0" encoding="UTF-8"?>
<ticket><ctrl><agentid>0006297</agentid><cmd>1006</cmd><md>aaaa</md></ctrl><body><lot orderid="123343" lotno="F47104" issue="2011009" betcode="0001010203040506~01^" amount="200"/></body></ticket>

读取程序:
package com.jrt.common;

import java.io.File;
import java.io.FileWriter;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class ReadXml {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			readXml("c:/agent.xml");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static int formatXMLFile(String filename){

	       int returnValue = 0;

	       try{

	           SAXReader saxReader = new SAXReader();

	           Document document = saxReader.read(new File(filename));

	           XMLWriter writer = null;

	           /** 格式化输出,类型IE浏览一样 */

	          OutputFormat format = OutputFormat.createPrettyPrint();

	           /** 指定XML编码 */

	           format.setEncoding("GBK");

	           writer= new XMLWriter(new FileWriter(new File(filename)),format);
               
	           writer.write(document);

	           writer.close();     

	           /** 执行成功,需返回1 */

	           returnValue = 1;    

	       }catch(Exception ex){

	           ex.printStackTrace();

	       }

	       return returnValue;

	    }
	
	public static void readXml(String xml) throws Exception{
		SAXReader read=new SAXReader();
		Document doc=read.read(new File(xml));
		Element root=doc.getRootElement();
		Element ctrl=root.element("ctrl");
		String agentid=ctrl.element("agentid").getText();
		System.out.println(agentid);
		String cmd=ctrl.element("cmd").getText();
		String md=ctrl.element("md").getText();
		System.out.println(cmd);
		System.out.println(md);
		Element body=root.element("body");
		//Element lot=body.element("lot");
		Element lot=(Element) body.elements().get(0);
		String lotno=lot.attributeValue("lotno"); 
		System.out.println(lotno);
		String issue=lot.attributeValue("issue"); 
		System.out.println(issue);
		String betcode=lot.attributeValue("betcode"); 
		System.out.println(betcode);
		String amount=lot.attributeValue("amount"); 
		System.out.println(amount);
		String orderid=lot.attributeValue("orderid"); 
		System.out.println(orderid);
	}
}

你可能感兴趣的:(C++,c,xml,IE,C#)