注:最近在写xml操作这块东西,中间遇到了一些坑 其中就包含下面一个 遇到xml文件包含 命名空间或者注释 这时反序列化 会报错。下面就是解决方案
//创建xml文档
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\Users\Tony\Downloads\统一标准报文格式.xml");
//去掉注释 和命名空间
string newXml = System.Text.RegularExpressions.Regex.Replace(
xmlDoc.OuterXml,
@"(xmlns:?[^=]*=[""][^""]*[""])", "",
System.Text.RegularExpressions.RegexOptions.IgnoreCase |
System.Text.RegularExpressions.RegexOptions.Multiline);
//这里是反序列化成实体
root info= XmlHelper.ToObject<root>(newXml);
/// <summary>
/// XML帮助类
/// </summary>
public class XmlHelper
{
/// <summary>
/// xml转实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="content">xml字符串</param>
/// <returns></returns>
public static T ToObject<T>(string content) where T : new()
{
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)))
{
XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
return (T)xmlFormat.Deserialize(stream);
}
} /// <summary>
/// 实体转xml
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string ToXml<T>(T t) where T : new()
{
XmlSerializer xmlSerializer = new XmlSerializer(t.GetType());
Stream stream = new MemoryStream();
xmlSerializer.Serialize(stream, t);
stream.Position = ;
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
return text;
}
}