Java实现数据库数据生成XML文件的通用程序

转载 2013年12月05日 11:22:37
转自http://tieba.baidu.com/p/136643159

原篇内容缺失,本篇对其进行整理,以备后用。

本篇使用w3c.dom解析。方法实现将查询结果集(ResultSet对象)和要生成的XML文件的路径传人,然后自己指派属性名称、元素名称并与对应的查询结果集中的字段对应,最后调用designOver()函数生成所期望的XML文件。

方法包含5个类:CreateXmlFile.java, XmlDisposal.java, SaveAttrName.java, SaveEleName.java, WriteXmlFile.java。

SaveAttrName.java:

public class SaveAttrName {
	private String attrName;
	private int index;
	public SaveAttrName(String attrName, int index) {
		super();
		this.attrName = attrName;
		this.index = index;
	}
	public String getAttrName() {
		return attrName;
	}
	public void setAttrName(String attrName) {
		this.attrName = attrName;
	}
	public int getIndex() {
		return index;
	}
	public void setIndex(int index) {
		this.index = index;
	}
	
}

SaveEleName.java:

public class SaveEleName {
	private String eleName;
	private int index;
	public SaveEleName(String eleName, int index) {
		super();
		this.eleName = eleName;
		this.index = index;
	}
	public String getEleName() {
		return eleName;
	}
	public void setEleName(String eleName) {
		this.eleName = eleName;
	}
	public int getIndex() {
		return index;
	}
	public void setIndex(int index) {
		this.index = index;
	}
	
}

XmlDisposal.java:

public class XmlDisposal {

	private ResultSet rs; //查询结果集 
	private String url; //要生成的xml文件的路径
	private ArrayList attrList = new ArrayList(); //用来存储属性名和字段索引的集合类 
	private ArrayList eleList = new ArrayList(); //用来存储元素名和字段索引的集合类
	private String root;
	private String rootChild;
	
	public void setResultSet(ResultSet rs, String url) {
		this.rs = rs;
		this.url = url;
	}
	
	public void setRootName(String root, String rootChild) {
		this.root = root;
		this.rootChild = rootChild;
	}
	
	public void collectData(String nameStr, int index, String type) {
		if(type.equals("attribute")) {
			attrList.add(new SaveAttrName(nameStr, index));
		} else {
			eleList.add(new SaveEleName(nameStr, index));
		}
	}
	
	public void startWrite() {
		new WriteXmlFile(attrList, eleList, rs, url).create(root, rootChild);
	}
}

WriteXmlFile.java:

public class WriteXmlFile {

	private ResultSet rs;
	private String url;
	private ArrayList arrtList;
	private ArrayList elemList;

	public WriteXmlFile(ArrayList arrtList,
			ArrayList elemList, ResultSet rs, String url) {
		super();
		this.rs = rs;
		this.url = url;
		this.arrtList = arrtList;
		this.elemList = elemList;
	}

	/**
	 * @param root xml文件的根元素名
	 * @param rootchild
	 */
	public void create(String root, String rootChild) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		Document document = null;
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			document = (Document) db.newDocument();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Element rootElem = document.createElement(root);
		document.appendChild(rootElem);
		Iterator attr = arrtList.iterator();
		Iterator elem = elemList.iterator();
		try {
			while (rs.next()) {
				Element rootChildElem = document.createElement(rootChild);
				while (attr.hasNext()) {
					// 循环到属性集合中取元素名称,之后从查询结果集中取得数据,创建元素属性
					SaveAttrName temp = (SaveAttrName) attr.next();
					rootChildElem.setAttribute(temp.getAttrName(), rs
							.getString(temp.getIndex()).trim());
				}
				rootElem.appendChild(rootChildElem);
				while (elem.hasNext()) {
					// 循环到元素集合中取元素名称,之后从查询结果集中取得数据,创建结点
					SaveEleName temp = (SaveEleName) elem.next();
					Element tempElem = document
							.createElement(temp.getEleName());
					Text tempTextElem = document.createTextNode(rs.getString(
							temp.getIndex()).trim());
					tempElem.appendChild(tempTextElem);
					rootChildElem.appendChild(tempElem);
				}
				attr = arrtList.iterator(); // 重复循环到集合中取值
				elem = elemList.iterator(); // 重复循环到集合中取值
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		writeXml(document);
	}

	private void writeXml(Document doc) {
		try {
			FileOutputStream out = new FileOutputStream(url);
			OutputStreamWriter outWriter = new OutputStreamWriter(out);
			((XmlDocument) doc).write(outWriter, "UTF-8");
			outWriter.close();
			out.close();
			System.out.print("\nWrite xmlfile successful!\n");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

注明:XmlDocument这个类的使用需要引入crimson.jar


CreateXmlFile.java

public class CreateXmlFile {

	private ResultSet rs; //查询结果集     
	 private String url;  //要生成的xml文件的路径     
	private XmlDisposal disposal; //自定义的用来收集和处理数据的类
	private String root; //xml文件的根元素名称
	private String rootChild; //根结点的子结点的元素名称 
	public CreateXmlFile(ResultSet rs, String url) {
		super();
		this.rs = rs;
		this.url = url;
		disposal = new XmlDisposal();
		disposal.setResultSet(this.rs, this.url);
	}
	
	//设定xml文件的根元素名称
	public void setRootEleName(String root, String rootChild) {
		this.root = root;
		this.rootChild = rootChild;
		disposal.setRootName(this.root, this.rootChild);
	}
	
	//设置属性的名字和索引位置,位置从1开始
	public void serAttrName(String nameStr, int index) {
		disposal.collectData(nameStr, index, "attribute");
	}
	
	//设置元素的名字和索引位置,位置从1开始 
	public void setEleName(String nameStr, int index) {
		disposal.collectData(nameStr, index, "element");
	}
	
	public void designOver() {
		disposal.startWrite();
	}
}

测试类test.java

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Connection conn = DBUtil.getConnection();
		Statement stmt;
		try {
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(DBUtil.getSql());
			/*int columnCount = rs.getMetaData().getColumnCount();
			while (rs.next()) {
				//rs.afterLast();
				//System.out.println(rs.getRow());
				for (int i = 1; i <= columnCount; i++) {
					System.out.print(rs.getObject(i) + "\t");	           
	                
				}
				
			}*/
			CreateXmlFile xml = new CreateXmlFile(rs, "d:/demo.xml");
			xml.setRootEleName("books","book"); 
			xml.serAttrName("title", 1);
                        //xml.setEleName("title", 1);
			xml.setEleName("author", 2);
			xml.setEleName("year", 3);
			xml.setEleName("price", 4);
			xml.designOver();
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

在D盘根目录下生成demo.xml文件:

<?xml version="1.0" encoding="UTF-8"?>

<books>
  <book title="Harry Potter">
    <author>J K. Rowling</author>
    <year>2005-01-01</year>
    <price>30</price>
  </book>
  <book title="Everyday Italian">
    <author>Giada De Laurentiis</author>
    <year>2005-01-01</year>
    <price>30</price>
  </book>
  <book title="Learning XML">
    <author>Erik T. Ray</author>
    <year>2003-01-01</year>
    <price>40</price>
  </book>
  <book title="XQuery Kick Start">
    <author>James McGovern, Per Bothner</author>
    <year>2003-01-01</year>
    <price>50</price>
  </book>
</books>

数据库book表记录如下:

+-------------------+-----------------------------+------+-------+
| title             | author                      | year | price |
+-------------------+-----------------------------+------+-------+
| Harry Potter      | J K. Rowling                | 2005 | 30    |
| Everyday Italian  | Giada De Laurentiis         | 2005 | 30    |
| Learning XML      | Erik T. Ray                 | 2003 | 40    |
| XQuery Kick Start | James McGovern, Per Bothner | 2003 | 50    |
+-------------------+-----------------------------+------+-------+
4 rows in set




相关文章推荐

强大的 将XML文件的数据导入到数据库的 程序 只需输入xml文件名即可自动创建

通过网上查资料并经过多天整理好的一个程序,以供需要的朋友学习: 前台:     后台: using System; using System.Collections.Generic; u...

【SSH】利用applicationContext.xml文件结合java代码生成项目所需的数据库

实现步骤: 查看项目的applicationContext.xml配置文件,我的如下(关键代码用红色表示): <property name="driverClassName" valu...

java读取XML文件通用工具类(递归调用)

java读取XML文件通用工具类(递归调用) 源代码下载地址:http://www.zuidaima.com/share/1550463285480448.htm
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)