C# XmlSerializer将类变成XML

使用XmlSerializer将类序列化成xml,记录下来方便以后查询

[Serializable]
    [XmlRoot]
    public class Parameter
    {
        [XmlElement]
        public string Name { get; set; }

        [XmlElement]
        public string Value { get; set; }
    }

    [Serializable]
    public class Flow
    {
        public Flow()
        {
            Parameters = new List<Parameter>();
        }

        [XmlElement]
        public string ID { get; set; }

        [XmlElement]
        public string Text { get; set; }

        //这里用XmlArray,会产生一个Parameters节点,其内部有多个Parameter节点; 若用XmlElement,会产生多个Parameters节点,没有Parameter节点
        [XmlArray]
        public List<Parameter> Parameters { get; set; }

        [XmlElement]
        public string Return { get; set; }
    }
    public static class Tool
    {
        public static T ReadXml<T>(this string content)
        {
            T result = default(T);
            try
            {
                XmlSerializer mySerializer = new XmlSerializer(typeof(T));
                using (TextReader reader = new StringReader(content))
                {
                    result = (T)mySerializer.Deserialize(reader);
                    reader.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return result;
        }
    }
    class Program
    {
        static string CreateXml()
        {
            var flow = new Flow { ID = "1001", Text = "Create", Return = "false" };
            flow.Parameters.Add(new Parameter { Name = "name1", Value = "value1" });
            flow.Parameters.Add(new Parameter { Name = "name2", Value = "value2" });
            XmlSerializer FlowSerial = new XmlSerializer(typeof(Flow));
            StringWriter sw = new StringWriter();
            FlowSerial.Serialize(sw, flow);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sw.ToString());
            sw.Flush();
            doc.DocumentElement?.SetAttribute("xml:space", "preserve"); //为了增加xml:space="preserve"

            StringWriter xmlsw = new StringWriter();
            doc.Save(xmlsw);
            return xmlsw.ToString();
        }
        static void Main(string[] args)
        {
            string xml = CreateXml();
            Console.WriteLine(xml);
            Console.WriteLine("---------------------------------------------------------------------");

            var flowclass = xml.ReadXml<Flow>();
            Console.WriteLine(flowclass.ID);
            Console.WriteLine(flowclass.Return);
            Console.WriteLine(flowclass.Text);
            foreach(var para in flowclass.Parameters)
            {
                Console.WriteLine(para.Name + " " + para.Value);
            }
        }
    }

 

上一篇:JavaScript:基本概念、变量


下一篇:Java 和 ABAP 中的几种引用类型的分析和比较