如何将查询结果集映射为 xml格式的数据?
映射文件:
<!-- mapping to xml data --> <select id="selectXmlData" resultClass="xml" xmlResultName="Product" parameterClass="int"> <![CDATA[ select * from t_product where prd_id=#value# ]]> </select> <select id="selectXmlDatas" resultClass="xml" xmlResultName="Product"> <![CDATA[ select prd_id as id, prd_description as description, prd_price as price from t_product ]]> </select> <!-- END mapping to xml data-->
DAO层:
public Object getXmlData(int id) throws SQLException {
init();
Object obj = (Object)sqlMapClient.queryForObject("selectXmlData", id);
return obj;
}
public List getXmlDatas() throws SQLException {
init();
List list = (List)sqlMapClient.queryForList("selectXmlDatas");
return list;
}
测试类:
public class ProductTest {
ProductDAO productDao = new ProductDAOImpl();
public static void main(String[] args) throws SQLException {
ProductTest ptest = new ProductTest();
ptest.getXmlData(1);
System.out.println("-------------------");
ptest.getXmlDatas();
}
/**
* 获得XML格式的数据
* @throws SQLException
*/
public void getXmlData(int id) throws SQLException{
// 查找t_product表,将其结果映射到xml!
// 返回值是xml形式的字符串
Object obj = (Object) productDao.getXmlData(1);
if(obj instanceof Product) {
System.out.println("return type is Product");
}else if(obj instanceof String) {
System.out.println("return type is String");
}else {
System.out.println("return type is unknow");
}
System.out.println(obj);
}
public void getXmlDatas() throws SQLException {
List list = (List)productDao.getXmlDatas();
Iterator i = list.iterator();
while(i.hasNext()) {
Object obj = i.next();
System.out.println(obj.getClass());
}
System.out.println(list);
}
}
结果:
return type is String
<?xml version="1.0" encoding="UTF-8"?>
<Product>
<prd_id> 1 </prd_id>
<prd_description>basketball</prd_description>
<prd_price>206.99</prd_price>
</Product>
-------------------
class java.lang.String
class java.lang.String
[<?xml version="1.0" encoding="UTF-8"?>
<Product>
<id> 1</id>
<description>basketball</description>
<price>206.99</price>
</Product>,
<?xml version="1.0" encoding="UTF-8"?>
<Product>
<id> 2 </id>
<description>football</description>
<price>106.99</price>
</Product>]