最近处理数据的时候用到了Xml和其他数据之间的转换,所以整理了一些方法。
class XMLHelper
{
/// <summary>
/// 读取xml模板
/// </summary>
/// <param name="filename">相对路径</param>
/// <returns></returns>
public static string Getmsg(string filename)
{
XmlDocument xmldoc = new XmlDocument();
string path = AppDomain.CurrentDomain.BaseDirectory;
string strUrl = path + filename;
xmldoc.Load(strUrl);
return xmldoc.InnerXml;
}
public static XmlDocument GetXmlDoc(string fielName)
{
XmlDocument xmldoc = new XmlDocument();
string path = AppDomain.CurrentDomain.BaseDirectory;
string strUrl = path + fielName;
xmldoc.Load(strUrl);
return xmldoc;
}
public static XmlDocument GetXmlDocument(string xml)
{
XmlDocument xmlDoc = new XmlDocument();
if (!string.IsNullOrEmpty(xml))
{
xmlDoc.LoadXml(xml);
}
return xmlDoc;
}
#region 序列化
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="obj">对象</param>
/// <returns></returns>
public static string Serializer(Type type, object obj)
{
MemoryStream Stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(type);
try
{
//序列化对象
xml.Serialize(Stream, obj);
}
catch (InvalidOperationException)
{
throw;
}
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd(); sr.Dispose();
Stream.Dispose(); return str;
} #endregion
//反序列化
//接收2个参数:xmlFilePath(需要反序列化的XML文件的绝对路径),type(反序列化XML为哪种对象类型)
public static object DeserializeFromXml(string xml, Type type)
{
object result = null;
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
MemoryStream ms = new MemoryStream();
xmlDoc.Save(ms);
ms.Seek(0, SeekOrigin.Begin);
XmlSerializer xs = new XmlSerializer(type);
result = xs.Deserialize(ms);
}
catch (Exception ex)
{
throw;
}
return result;
} /// <summary>
/// XML转换成DataTable
/// </summary>
/// <param name="xmlStr"></param>
/// <returns></returns>
public static DataTable XmlToDataTable(string xmlStr)
{
if (!string.IsNullOrEmpty(xmlStr))
{
StringReader StrStream = null;
XmlTextReader Xmlrdr = null;
try
{
DataSet ds = new DataSet();
//读取字符串中的信息
StrStream = new StringReader(xmlStr);
//获取StrStream中的数据
Xmlrdr = new XmlTextReader(StrStream);
//ds获取Xmlrdr中的数据
ds.ReadXml(Xmlrdr);
return ds.Tables[0];
}
catch (Exception ex)
{
throw;
}
finally
{
//释放资源
if (Xmlrdr != null)
{
Xmlrdr.Close();
StrStream.Close();
StrStream.Dispose();
}
}
}
return null;
}
/// <summary>
/// 格式化XML
/// </summary>
/// <param name="format">XML</param>
/// <param name="arg">传递DataRow可以直接格式化,也可以自己实现IFormatProvider</param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public static string Format(string format, object arg)
{
char[] preChar = new char[] { '{' };
char[] endChar = new char[] { '}' };
DataRow row = arg as DataRow;
if (row != null)
{
var RegexStr = string.Format("{0}.+?{1}", string.Join("", preChar.ToArray()), string.Join("", endChar.ToArray()));
Regex reg = new Regex(RegexStr);
MatchCollection matchList = reg.Matches(format);
for (int i = 0; i < matchList.Count; i++)
{
string fieldName = matchList[i].ToString().TrimStart(preChar).TrimEnd(endChar);
string fieldVal = string.Empty;
if (row.Table.Columns.Contains(fieldName))
{
fieldVal = row[fieldName].ToString();
}
format = format.Replace(matchList[i].ToString(), fieldVal);
} } return format;
}
}