xml映射为object对象,同时object对象,以xml来表示:

    public class Tools
{
private static XmlNodeList SelectNodes(string xpath, string path)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
return doc.SelectNodes(xpath);
}
private static XmlNode SelectSingleNode(string xpath, string path)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
return doc.SelectSingleNode(xpath);
} public static T SelectSingle<T>(string selectNode, string path) where T : IxmlToObject<T>, new()
{
T item = new T(); var node = SelectSingleNode(selectNode, path); if (node != null)
{
T obj = item.XmlToObject(node); }
return item;
}
public static void SaveXml(IxmlFormat obj, string path)
{
XmlDocument doc = new XmlDocument();
var xml = obj.ToXml();
doc.LoadXml(xml);
doc.Save(path);
} public static List<T> SelectList<T>(string selectNode,string path) where T:new()
{
List<T> items = new List<T>(); var nodes = SelectNodes(selectNode,path); if (nodes != null)
{
var type = typeof(T);
var properties = type.GetProperties().ToList(); foreach (XmlNode node in nodes)
{
T config = new T(); foreach (XmlAttribute a in node.Attributes)
{
string name = a.Name;
string value = a.Value; var p = properties.FirstOrDefault(t => t.Name.ToLower() == name.ToLower()); if (p != null)
{
p.SetValue(config, value, null);
}
}
items.Add(config);
}
}
return items;
} public static string ReplaceSpecialChars(string content)
{
if (string.IsNullOrEmpty(content)) return ""; string[] specialChars = { "&", "<", ">", "\"", "'" };
string[] entities = { "&amp;", "&lt;", "&gt;", "&quot;", "&apos;" }; int i = ;
foreach (var item in specialChars)
{
content = content.Replace(item, entities[i]);
i++;
}
return content;
}
}

这是公共的接口:

    public interface IxmlFormat
{
string ToXml();
}
public interface IxmlToObject<T>
{
T XmlToObject(XmlNode node);
}

下面是自定义Object对象对接口的实现:

public class TestCase : IxmlFormat, IxmlToObject<TestCase>
{
public string Title { set; get; }
public string Author { set; get; }
public string BibType { set; get; }
/// <summary>
/// 测试用例路径
/// </summary>
public string FilePath { set; get; } public List<SearchResult> StandardResults { set; get; } public List<SearchResult> SearchResults { set; get; } public string ToXml()
{
var title = Tools.ReplaceSpecialChars(this.Title);
var author = Tools.ReplaceSpecialChars(this.Author);
var bibType = Tools.ReplaceSpecialChars(this.BibType); StringBuilder sb = new StringBuilder(); sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); if (SearchResults != null && SearchResults.Count > )
{
sb.AppendFormat("<case title=\"{0}\" author=\"{1}\" bibType=\"{2}\" >", title, author, bibType); foreach (SearchResult item in SearchResults)
{
sb.AppendFormat("<item title=\"{0}\">", Tools.ReplaceSpecialChars(item.Title)); foreach (var fitem in item.Fields)
{
sb.AppendFormat("<field content=\"{0}\"/>", Tools.ReplaceSpecialChars(fitem));
}
sb.AppendFormat("</item>");
} sb.Append("</case>");
}
return sb.ToString();
} public TestCase XmlToObject(XmlNode node)
{
string title = node.Attributes["title"].Value;
string author = node.Attributes["author"].Value;
string bibType = node.Attributes["bibType"].Value; this.Title = title;
this.Author = author;
this.BibType = bibType; this.StandardResults = new List<SearchResult>();
XmlNodeList itemNodes = node.SelectNodes("//item");
foreach (XmlNode n in itemNodes)
{
var sr = new SearchResult()
{
Title = n.Attributes["title"].Value,
Fields = new List<string>()
}; var fileds = n.ChildNodes; foreach (XmlNode fn in fileds)
{
sr.Fields.Add(fn.Attributes["content"].Value);
}
this.StandardResults.Add(sr);
} return this;
}
} public class SearchResult
{
public string Title { set; get; } public List<string> Fields { set; get; } }

这是一个测试用例,程序从xml文件中读取测试用例,运行测试程序,完成后把结果保存到另外一个xml文件中,这个xml文件结构和测试用例的xml结构一样。我们看看如何读取测试用例:

        /// <summary>
/// 读取测试用例
/// </summary>
/// <returns></returns>
private static List<TestCase> GetTestCase(string caseDir)
{
List<TestCase> tests = new List<TestCase>(); var files = Directory.GetFiles(caseDir); foreach (var f in files)
{
var filePath = f;
var testCase = Tools.SelectSingle<TestCase>("//case", filePath);
testCase.FilePath = filePath;
tests.Add(testCase);
} return tests;
}

保存测试结果:

         TestCase t = new TestCase()
{
FilePath = viewModel.FilePath,
Author = viewModel.SearchAuthor,
Title = viewModel.SearchTitle,
BibType = viewModel.SearchType,
SearchResults = viewModel.TestResultData,
StandardResults = viewModel.StandardResults
}; string path = viewModel.TestResultFilePath + "\\" + viewModel.ResolveName; if (!Directory.Exists(path)) Directory.CreateDirectory(path); path += "\\" + Path.GetFileNameWithoutExtension(t.FilePath) + "_data.xml"; Tools.SaveXml(t, path);

注意:对象与xml之间的转换,再转为xml时,注意特殊符号的转义,否则会报错。

xml与object 之间的ORM的更多相关文章

  1. Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->使用spring framework的IoC容器功能----->方法一:使用XML文件定义beans之间的依赖注入关系

    XML-based configuration metadata(使用XML文件定义beans之间的依赖注入关系) 第一部分 编程思路概述 step1,在XML文件中定义各个bean之间的依赖关系. ...

  2. Django中ORM介绍和字段及字段参数 Object Relational Mapping(ORM)

    Django中ORM介绍和字段及字段参数   Object Relational Mapping(ORM) ORM介绍 ORM概念 对象关系映射(Object Relational Mapping,简 ...

  3. Object Relational Mapping(ORM)

    Object Relational Mapping(ORM) ORM介绍 ORM概念 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据 ...

  4. RCE via XStream object deserialization && SECURITY-247 / CVE-2016-0792 XML reconstruction Object Code Inject

    catalogue . Java xStream . DynamicProxyConverter . java.beans.EventHandler . RCE via XStream object ...

  5. JAXB 操作XML 与 Object

    Java Architecture for XML Binding) 是一个业界的标准,是一项能够依据XML Schema产生Java类的技术.是一种xml与object映射绑定技术标准. JDK5下 ...

  6. php中 xml json 数组 之间相互转换

    php中 xml json  数组 之间相互转换 1 数组转json $result = array( 'status' =>$status, 'message'=>$message, ' ...

  7. applicationContext.xml报错org.springframework.orm.hibernate3.LocalSessionFactoryBean not found

    applicationContext.xml报错org.springframework.orm.hibernate3.LocalSessionFactoryBean not found 解决办法: 1 ...

  8. java中Xml、json之间的相互转换

    旁白: 最近关于xml与json之间的转换都搞蒙了,这里写一个demo,以后备用. 正题: project格式是: jar包是一个一个检出来的,还算干净了. 代码: 工具类: package exer ...

  9. org.json里实现XML和JSON之间对象互转

    org.json包里有一个类org.json.XML可以实现XML和JSON之间的转换.http://www.json.org/javadoc/org/json/XML.html JSONObject ...

随机推荐

  1. iOS中的两种搜索方式UISearchDisplayController和UISearchController

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 以前iOS的搜索一般都使用UISearchDisplayCon ...

  2. (NO.00005)iOS实现炸弹人游戏(九):游戏主角(二)

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 上篇介绍了游戏主角的初始化方法,下面我们一次来实现主角的其他方 ...

  3. Struts2配置问题终极解决方案

    从下午忙到现在,终于找到问题的根源了.写下此文,与君共勉. 我的目录结构是这样的. 关于配置文件加载问题 控制台下面报错,提示错误信息如下: 严重: Exception starting filter ...

  4. 开源项目——小Q聊天机器人V1.1

    小Q聊天机器人V1.0 http://blog.csdn.net/baiyuliang2013/article/details/51386281 小Q聊天机器人V1.1 http://blog.csd ...

  5. Android开发学习之路--Activity之Intent

    窗外再次飘起了小雪,还有1周就过年了,2016年即将到来,来年不知道自己将身处何处,船到桥头自然直吧.还是继续学习吧,上次学习了Activity,那么如果是两个Activity之间,怎么从一个Acti ...

  6. iOS中 断点下载详解 韩俊强的博客

    布局如下: 基本拖拉属性: #import "ViewController.h" #import "AFNetworking.h" @interface Vie ...

  7. 【一天一道LeetCode】#86. Partition List

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  8. Java Map 及相应的一些操作总结

    Map是我们在开发的时候经常会用到的,大致有以下几个操作,其中putAll方法是针对集合而言的操作,故不再进行说明,下面请看一下常用的知识点吧,尤其是keySet和Values两个方法及相应值的获取方 ...

  9. ISLR系列:(4.1)模型选择 Subset Selection

    Linear Model Selection and Regularization 此博文是 An Introduction to Statistical Learning with Applicat ...

  10. 12_Android中HttpClient的应用,doGet,doPost,doHttpClientGet,doHttpClient请求,另外借助第三方框架实现网络连接的应用,

     准备条件, 编写一个web项目.编写一个servlet,若用户名为lisi,密码为123,则返回"登录成功",否则"登录失败".项目名为ServerIth ...