编程语言
首页 > 编程语言> > C# XmlSerializer将类变成XML

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);
            }
        }
    }

 

标签:XML,Console,string,Parameters,C#,WriteLine,new,XmlSerializer,public
来源: https://blog.csdn.net/gdizcm/article/details/113799877