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 ...
随机推荐
- 用API给用户添加职责
DECLARE lc_user_name VARCHAR2(100) := 'PRAJ_TEST'; lc_resp_appl_short_name VARCHAR2(100) := 'FND' ...
- 01基于配置文件方式的SpringMVC,三种HandlerMapping,三种控制器
1 添加Spring MVC所需的jar包. 2 创建一个以下项目结构的springmvc项目 3 web.xml的配置如下: <?xmlversion="1.0"en ...
- javascript之cookie对象
属性 name 唯一必须设置的属性,表示cookie的名称 expires 指定cookie的存活周期,如不设置,浏览器关闭自动失效 path 决定c ...
- 【设计模式】java设计模式总述及观察者模式
今天在准备腾讯的面试时想起来要复习一下设计模式,而刚好前几天在参加网易的在线考试的时候,也出了一道关于设计模式的选择题,主要是考察观察者模式,虽然那道题自己做对了,但觉得还是应该好好总结一下设计模式的 ...
- 如何在Cocos2D游戏中实现A*寻路算法(四)
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;) 免责申明:本博客提供的所有翻译文章原稿均来自互联网,仅供学习交流 ...
- Android下资源使用的方式-android学习之旅(五十三)
访问资源分为在java和xml中访问
- iOS中 UIMPMediaPickerController播放系统音乐
布局如下: 引入框架: #import <AVFoundation/AVFoundation.h> #import <MediaPlayer/MediaPlayer.h> 遵循 ...
- 06_Android中ArrayAdapter的使用
1 目标界面 2 编写AndroidManifest.xml文件 <?xml version="1.0" encoding="utf-8"?> ...
- linux 下检查java jar包 程序是否正常 shell
linux 下检查java jar包 程序是否正常 shell http://injavawetrust.iteye.com BATCH_SERVER="batch.jar" NR ...
- 推荐一个优秀的c++源代码,TinyXml2
项目主页:http://grinninglizard.com/tinyxml2docs/index.html tinyxml2.h /* Original code by Lee Thomason ( ...