注:最近在写xml操作这块东西,中间遇到了一些坑 其中就包含下面一个 遇到xml文件包含 命名空间或者注释 这时反序列化 会报错。下面就是解决方案
1 //创建xml文档 2 XmlDocument xmlDoc = new XmlDocument(); 3 xmlDoc.Load(@"C:\Users\Tony\Downloads\统一标准报文格式.xml"); 4 //去掉注释 和命名空间 5 string newXml = System.Text.RegularExpressions.Regex.Replace( 6 xmlDoc.OuterXml, 7 @"(xmlns:?[^=]*=[""][^""]*[""])", "", 8 System.Text.RegularExpressions.RegexOptions.IgnoreCase | 9 System.Text.RegularExpressions.RegexOptions.Multiline); 10 //这里是反序列化成实体 11 root info= XmlHelper.ToObject<root>(newXml);
1 /// <summary> 2 /// XML帮助类 3 /// </summary> 4 public class XmlHelper 5 { 6 /// <summary> 7 /// xml转实体 8 /// </summary> 9 /// <typeparam name="T"></typeparam> 10 /// <param name="content">xml字符串</param> 11 /// <returns></returns> 12 public static T ToObject<T>(string content) where T : new() 13 { 14 using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content))) 15 { 16 XmlSerializer xmlFormat = new XmlSerializer(typeof(T)); 17 return (T)xmlFormat.Deserialize(stream); 18 } 19 } 20 21 /// <summary> 22 /// 实体转xml 23 /// </summary> 24 /// <typeparam name="T"></typeparam> 25 /// <param name="t"></param> 26 /// <returns></returns> 27 public static string ToXml<T>(T t) where T : new() 28 { 29 XmlSerializer xmlSerializer = new XmlSerializer(t.GetType()); 30 Stream stream = new MemoryStream(); 31 xmlSerializer.Serialize(stream, t); 32 stream.Position = 0; 33 StreamReader reader = new StreamReader(stream); 34 string text = reader.ReadToEnd(); 35 return text; 36 } 37 }