导航

Xml对象化框架

Posted on 2007-05-17 20:45  Centorier  阅读(439)  评论(1)    收藏  举报
现在成熟的数据访问框架有很多,如IBatisNet、NHibernate等,但很少见到有Xml访问的框架。前段时间由于工作的需要,需要对大量Xml文件进行操作,于是自己写了一个简单的Xml访问的框架。
假设有如下Xml文件:
<?xml version="1.0" encoding="utf-8" ?>
<Class>
  
<Student id="001" name="zhang">
    
<grade>98</grade>
    
<grade>88</grade>
    
<grade>78</grade>
  
</Student>
  
<Student id="002" name="wang">
    
<grade>99</grade>
    
<grade>77</grade>
    
<grade>88</grade>
  
</Student>
  
<Student id="003" name="chen">
    
<grade>100</grade>
    
<grade>89</grade>
    
<grade>72</grade>
  
</Student>
</Class>
我们需要得到Student的相关信息,包括id、name和grade。
于是,我们可以新建Student实体类:
using System;
using System.Collections.Generic;
using XmlMapper;
using XmlMapper.XmlExpression;

namespace Test
{
    [Node(
"Student.xml""Class/Student")]
    
public class Student
    
{
        
private string _id;

        [Field(
"""id")]
        
public string ID
        
{
            
get return this._id; }
            
set this._id = value; }
        }


        
private string _name;

        [Field(
"""name")]
        
public string Name
        
{
            
get return this._name; }
            
set this._name = value; }
        }


        
private string[] _grade;

        [Field(
"grade""")]
        
public string[] Grade
        
{
            
get return this._grade; }
            
set this._grade = value; }
        }


        
public static IList<Student> GetList()
        
{
            IList
<Student> list = Mapper.Handle.List<Student>();
            
return list;
        }


        
public static Student GetObject(string id)
        
{
            Student obj 
= Mapper.Handle.Add(Expression.Eq("ID", id)).Get<Student>();
            
return obj;
        }

    }

}

在Student类上添加特性Node,参数一指定Xml路径,参数二指定跟节点,这样就让该类与Xml文件建立了映射关系。
给访问器ID、Name、Grade添加Field特性,指定其在Xml的属性,其中参数一指定Xml路径,参数二指定Attribute,如果要得到的是InnerText,则参数二为空。
这样,映射关系建立完成。
在查询时添加条件的方法同NHibernate一样,例如上面要得到某特定ID的学生信息,可以Add(Expression.Eq(id))来添加查询条件。
最后调用Mapper.Handle.List和Get方法就可以得到结果。

测试代码及XmlMapper.dll/Files/centorier/Test.rar
稍后放出源代码