xml与object 之间的ORM
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 = { "&", "<", ">", """, "'" }; 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的更多相关文章
- Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->使用spring framework的IoC容器功能----->方法一:使用XML文件定义beans之间的依赖注入关系
XML-based configuration metadata(使用XML文件定义beans之间的依赖注入关系) 第一部分 编程思路概述 step1,在XML文件中定义各个bean之间的依赖关系. ...
- Django中ORM介绍和字段及字段参数 Object Relational Mapping(ORM)
Django中ORM介绍和字段及字段参数 Object Relational Mapping(ORM) ORM介绍 ORM概念 对象关系映射(Object Relational Mapping,简 ...
- Object Relational Mapping(ORM)
Object Relational Mapping(ORM) ORM介绍 ORM概念 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据 ...
- 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 ...
- JAXB 操作XML 与 Object
Java Architecture for XML Binding) 是一个业界的标准,是一项能够依据XML Schema产生Java类的技术.是一种xml与object映射绑定技术标准. JDK5下 ...
- php中 xml json 数组 之间相互转换
php中 xml json 数组 之间相互转换 1 数组转json $result = array( 'status' =>$status, 'message'=>$message, ' ...
- applicationContext.xml报错org.springframework.orm.hibernate3.LocalSessionFactoryBean not found
applicationContext.xml报错org.springframework.orm.hibernate3.LocalSessionFactoryBean not found 解决办法: 1 ...
- java中Xml、json之间的相互转换
旁白: 最近关于xml与json之间的转换都搞蒙了,这里写一个demo,以后备用. 正题: project格式是: jar包是一个一个检出来的,还算干净了. 代码: 工具类: package exer ...
- org.json里实现XML和JSON之间对象互转
org.json包里有一个类org.json.XML可以实现XML和JSON之间的转换.http://www.json.org/javadoc/org/json/XML.html JSONObject ...
随机推荐
- linux下字节对齐
一,内存地址对齐的概念 计算机内存中排列.访问数据的一种方式,包含基本数据对齐和结构体数据对齐. 32位系统中,数据总线宽度为32,每次能够读取4字节数据.地址总线为32,最大寻址空间为4 ...
- iOS中让Settings Bundle中的变化立即在App中反应出来的两种方法
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 为了能够在Settings Bundle中的变化在进入App后 ...
- RecyclerView下拉刷新上拉加载(三)—对Adapter的封装
RecyclerView下拉刷新上拉加载(一) http://blog.csdn.net/baiyuliang2013/article/details/51506036 RecyclerView下拉刷 ...
- Eclipse 主题
Eclipse开发环境默认都是白底黑字的,看到同事的Xcode中设置的黑灰色背景挺好看的,就去网络上查了一下.发现Eclipse也可以设置主题. http://eclipsecolorthemes.o ...
- listview下拉刷新上拉加载扩展(三)-仿最新版美团外卖
本篇是基于上篇listview下拉刷新上拉加载扩展(二)-仿美团外卖改造而来,主要调整了headview的布局,并加了两个背景动画,看似高大上,其实很简单: as源码地址:http://downloa ...
- Cocos2D旋转炮塔到指定角度(三)
到目前为止都很美好! 但是却有一点奇怪,因为炮塔一下子跳转到指定位置去射击,并不是平滑的跟随触摸去转动到指定位置.你可以修复这个问题,但是这需要略微一点的重构(refactoring). 首先打开He ...
- UIActionSheet,UIAlertView技术分享
UIActionSheet #import "FirstViewController.h" @interface FirstViewController ()<UIActio ...
- Java将网络地址对应的图片转成本地的图片
只知道浏览器使用的是HTTP协议,那么如何将网络资源使用JavaHTTP下载下来呢! 这只是一个非常简单的小示例,只是不想每次碰到关于此方面的内容忘了就无从下手! 示例创建HttpURLConn ...
- Java解析XML与生成XML文件
XML是eXtensible Markup Language(可扩展标记语言)的简写形式,它是一种元标记语言(meta-markup language),也就是说它没有一套能够适用于各个领域中所有用户 ...
- C++对象模型(二):The Semantics of Copy Constructors(拷贝构造函数之编译背后的行为)
本文是 Inside The C++ Object Model's Chapter 2 的部分读书笔记. 有三种情况,需要拷贝构造函数: 1)object直接为另外一个object的初始值 2)ob ...