using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using System.Data;
using System.Linq;
using System.IO;
using System.Xml;

namespace OurMsg.Class.common


{

/**//// <summary>
/// XML 格式转换类
/// </summary>
public class XmlConvert

{

DeCode#region DeCode

/**//// <summary>
/// 检索单个子元素
/// </summary>
/// <param name="xmlData">xml 数据</param>
/// <param name="key">键名</param>
/// <returns></returns>
public static string ToString(string xmlData, string key)

{
try

{
XElement els = XElement.Parse(xmlData);
XElement e = els.Element(key);
return (e != null) ? e.Value : "";
}
catch (Exception)

{
return "";
}
}


/**//// <summary>
/// xml数据转换到Dictionary(键/值)
/// </summary>
/// <param name="xmlData">xml数据</param>
/// <returns></returns>
public static Dictionary<string, string> ToDictionary(string xmlData)

{
try

{
Dictionary<string, string> dict = new Dictionary<string, string>();
XElement els = XElement.Parse(xmlData);
foreach (XElement el in els.Elements())
dict.Add(el.Name.LocalName, el.Value);
return dict;
}
catch (Exception)

{
return new Dictionary<string, string>();
}
}


/**//// <summary>
/// 将 xml数据转换为DataSet
/// </summary>
/// <param name="xmlData">xml数据</param>
/// <returns></returns>
public static DataSet ToDataSet(string xmlData)

{
StringReader stream = null;
XmlTextReader reader = null;
DataSet xmlDS = new DataSet();
try

{
stream = new StringReader(xmlData);
//从stream装载到XmlTextReader
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader); //ps.此方法不支持 XmlReadMode.IgnoreSchema
}
catch (Exception)

{
}
finally

{
if (reader != null) reader.Close();
}

//保持数据有效
if (xmlDS.Tables.Count==0)

{
DataTable table = new DataTable();
xmlDS.Tables.Add(table);
}

return xmlDS;
}
#endregion


EnCode#region EnCode

/**//// <summary>
/// 单个数据生成 xml
/// </summary>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <returns></returns>
public static string ToXmlData(string key, string value)

{
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("root",
new XElement(key, value)
)
);

return doc.ToString();
}


/**//// <summary>
/// 集合数据生成 xml数据
/// </summary>
/// <param name="dictSend">Dictionary 集合</param>
/// <returns></returns>
public static string ToXmlData(Dictionary<string, string> dict)

{
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("root",
from keyValue in dict
select new XElement(keyValue.Key, keyValue.Value)
)
);

return doc.ToString();
}
#endregion


/**//// <summary>
/// xml传输 时间格式的一点格式化(建议取消)
/// </summary>
/// <param name="dtList"></param>
/// <param name="key"></param>
/// <param name="format"></param>
public static void DataTimeToString(DataTable dt, string key, string format)

{
foreach (DataRow row in dt.Rows)
row[key] = Convert.ToDateTime(row[key]).ToString(format);
}
}
}

posted on 2009-07-15 15:09
黄小二 阅读(330)
评论(0) 编辑 收藏 所属分类:
ASP.NET 、
C#