题目看起来像大杂烩啊,其实在项目里是同一部分的,都是处理XML相关的事情。
XML与实体对象的互相转换
// xml序列化公共处理类
public class XmlSerializeHelper
{
// 实体对象->XML
/* 可能有的报错:没有 Unicode 字节顺序标记
* 处理:<?xml version="1.0" encoding="utf-16"?> 删除encoding="utf-16"
*/
public static string XmlSerialize<T>(T obj)
{
try
{
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
Type t = obj.GetType();
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
sw.Close();
return sw.ToString();
}
}
catch (Exception ex)
{
throw new Exception("将实体对象转换成XML异常", ex);
}
}
// XML->实体对象
public static T DESerializer<T>(string strXML) where T : class
{
try
{
using (System.IO.StringReader sr = new System.IO.StringReader(strXML))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(sr) as T;
}
}
catch (Exception ex)
{
throw new Exception("将XML转换成实体对象异常", ex);
}
}
}
使用方法:
public class EnzymeInfo {
public string Name { get; set; }
public string Seq { get; set; } // 原始序列
public EnzymeInfo() { }
public EnzymeInfo(string name, string seq) {
Name = name;
Seq = seq;
}
}
public static void ListToXmlTest(string enzymeFilePath, string outFilePath) {
// GetEnzymeInfoList()这是我自己的函数,用来获取List<EnzymeInfo>
List<EnzymeInfo> enzymeInfos = GetEnzymeInfoList(enzymeFilePath);
// 将实体对象转换为XML
string xmlResult = XmlSerializeHelper.XmlSerialize(enzymeInfos);
// 存储
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outFilePath)) {
sw.Write(xmlResult);
}
// 反序列化
//List<EnzymeInfo> deResult = XmlSerializeHelper.DESerializer<List<EnzymeInfo>>(xmlResult);
}
可能有的bug:没有 Unicode 字节顺序标记
处理:<?xml version="1.0" encoding="utf-16"?> 删除encoding="utf-16"
使用LINQ从XML中查询
前面生成的XML文件,大致如图所示:
这里仅给出几个查询示例,更复杂的以后用到再更新吧:
查询所有的Name值并去重
List<string> names = new List<string>();
XElement xElement = XElement.Load(enzymeInfoFilePath); // 读取xml
var els = from el in xElement.Descendants("EnzymeInfo") // 查找所有Name
where true
select el.Element("Name").Value; // 这里才是string
names = els.ToList().Distinct().ToList(); // 去重
查找Name为指定值的元素
var els = from el in xElement.Descendants("EnzymeInfo")
where el.Element("Name").Value == name
select el;
foreach (var el in els) {
string shortSeq = el.Element("Seq").Value; // 取值
···
}