1 /// <summary> 2 /// XML幫助類 3 /// </summary> 4 public class XmlHelper 5 { 6 /// <summary> 7 /// xml轉實體 8 /// </summary> 9 /// <typeparam name="T"></t ...
註:最近在寫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 }View Code