澳门新葡萄京官网首页Xmlserializer序列和反序列化方法(XML格式)总结

string xmlString = Encoding.UTF8.GetString(ms.ToArray());

            return (T)mySerializer.Deserialize(mem2);
        }

using (XmlTextWriter xwriter = new XmlTextWriter(songlocation , null))
            {
                xwriter.WriteStartDocument();
                xwriter.WriteStartElement(“myplayer”);
                xwriter.WriteStartElement(“playingsongs”);
                xwriter.WriteAttributeString(“total”,songlist.Count
.ToString ());
                for (int i = 0; i < songlist.Count ;i++ )
                {
                    xwriter.WriteAttributeString(“song”+i.ToString
(),songlist[i ].ToString ());
                }
                xwriter.WriteEndElement();
                xwriter.WriteEndElement();
                xwriter.WriteEndDocument();
                xwriter.Flush();
                xwriter.Close();
            }

连续几日不成事,后来才晓得,不可能用 Encoding.UTF8,准确的应当是这么:

        [Conditional(“TRACE”)]
        private static void LogSaveFileException(string fileName, Exception ex)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(“Fail to save xml file: “);
            sb.Append(fileName + System.Environment.NewLine);
            sb.Append(ex.ToString());
            Logger.LogEvent(LogCategory, LogEventLoadFileException, sb.ToString());
        }
        #endregion
    }

来源:

  • Encoding.UTF8 与 new UTF8Encoding(false)有如何分别?
  • ASP.NET 与 XML-生成的 XML
    的编码

        /// <summary>
        /// XML & Datacontract Serialize & Deserialize Helper
        /// </summary>
        /// <typeparam name=”T”></typeparam>
        /// <param name=”serialObject”></param>
        /// <returns></returns>
        public static string XmlSerializer<T>(T serialObject) where T : class
        {
            XmlSerializer ser = new XmlSerializer(typeof(T));
            System.IO.MemoryStream mem = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8);
            ser.Serialize(writer, serialObject);
            writer.Close();

 

MemoryStream ms = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(ms, new
UTF8Encoding(false));

            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
            DataContractSerializer ser = new DataContractSerializer(typeof(T));
            T deserializedPerson = (T)ser.ReadObject(reader, true);
            reader.Close();
            stream.Close();

// 写入XML文档            

MemoryStream ms = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8);

writer.Indentation = 4;
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement(“root”);

writer.Flush();
writer.Close();

        /// <summary>
        /// serialize an object to a file.
        /// 
        /// </summary>
        /// <typeparam name=”T”></typeparam>
        /// <param name=”m_FileNamePattern”></param>
        /// <returns>
        /// loggingEnabled==true: log exception
        /// loggingEnabled==false: throw exception
        /// </returns>
        public static void SaveToXml<T>(string fileName, T data) where T : class
        {
            SaveToXml<T>(fileName, data, true);
        }        
 
        public static void SaveToXml<T>(string fileName, T data, bool loggingEnabled) where T : class
        {
            FileStream fs = null;
            try
            {

其一是自己的程序代码?请问怎样让写出的XML文件里都大器晚成行后生可畏行的!

有关阅读

                XmlSerializer serializer = new XmlSerializer(typeof(T));
                fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                serializer.Serialize(fs, data);
            }
            catch (Exception e)
            {
                if (loggingEnabled) LogSaveFileException(fileName, e);
                else throw;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

 

自己曾经是这样做的:

            return Encoding.UTF8.GetString(mem.ToArray());
        }

                writer = new XmlTextWriter(filePath,
System.Text.Encoding.UTF8);
                writer.Formatting
= Formatting.Indented;
                writer.WriteStartDocument();
                writer.WriteStartElement(“Log”);
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }

            return System.Text.UnicodeEncoding.UTF8.GetString(stream.ToArray());
        }
 
        #region Logging
        private const string LogCategory = “Framework.ObjectXmlSerializer”;
        private const int LogEventLoadFileException = 1;

            XmlTextWriter writer = null;
            try
            {

        [Conditional(“TRACE”)]
        private static void LogLoadFileException(string fileName, Exception ex)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(“Fail to load xml file: “);
            sb.Append(fileName + System.Environment.NewLine);
            sb.Append(ex.ToString());
            Logger.LogEvent(LogCategory, LogEventLoadFileException, sb.ToString());
        }

        public static T XmlDeserialize<T>(string str) where T : class
        {
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            StreamReader mem2 = new StreamReader(
                    new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str)),
                    System.Text.Encoding.UTF8);

 public class ObjectXmlSerializer
    {
        /// <summary>
        /// deserialize an object from a file.
        /// 
        /// 
        /// </summary>
        /// <typeparam name=”T”></typeparam>
        /// <param name=”m_FileNamePattern”></param>
        /// <returns>
        /// loggingEnabled==true: Null is returned if any error occurs.
        /// loggingEnabled==false: throw exception
        /// </returns>
        public static T LoadFromXml<T>(string fileName) where T : class
        {
            return LoadFromXml<T>(fileName, true);
        }
        
        public static T LoadFromXml<T>(string fileName, bool loggingEnabled) where T : class
        {
            FileStream fs = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                return (T)serializer.Deserialize(fs);
            }
            catch (Exception e)
            {
                if (loggingEnabled)
                {
                    LogLoadFileException(fileName, e);
                    return null;
                }
                else throw;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

XML作为数据交流格式已是很广阔了。那么大家平时要做的干活正是XML和目的之间人机联作转变,上边是部分方法的下结论:供之后参谋:

        public static T DataContractDeserializer<T>(string xmlData) where T : class
        {
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlData));

        public static string DataContractSerializer<T>(T myObject) where T : class
        {
            MemoryStream stream = new MemoryStream();
            DataContractSerializer ser = new DataContractSerializer(typeof(T));
            ser.WriteObject(stream, myObject);
            stream.Close();

            return deserializedPerson;
        }

发表评论

电子邮件地址不会被公开。 必填项已用*标注