/// <summary>
/// xml序列化
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="obj">值</param>
/// <returns></returns>
public static string XmlSerialize<T>(this T obj)
{
if (obj == null) throw new NullReferenceException("空");
var settings = new XmlWriterSettings()
{
OmitXmlDeclaration = true,//去掉xml声明
Encoding = Encoding.Default
};
var output = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(output, settings))
{
////去掉前缀和命名空间
var ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(writer, obj, ns);
}
return output.ToString();
}
/// <summary>
/// xml反序列化
/// </summary>
/// <typeparam name="T">返回对象类型</typeparam>
/// <param name="strXML">值</param>
/// <returns></returns>
public static T DeserializeXml<T>(this string strXML) where T : class
{
try
{
using (StringReader sr = new StringReader(strXML))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(sr) as T;
}
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 加<![CDATA[ ]]>数据字段
/// </summary>
[XmlIgnore] //方式1,这里属性设置忽略
public string HouseDetail { get; set; }
[XmlElement("Housedetail")]
public XmlNode[] CDataContent
{
get
{
if (HouseDetail!=null)
{
return new XmlNode[] {new XmlDocument().CreateCDataSection(HouseDetail)};
}
else
{
return null;
}
}
set
{
HouseDetail = value.First().Value;
}
}
特殊字符处理