在C#中正确解析XML文件

时间:2016-02-25 02:34:15

标签: c# asp.net .net xml

我试图读取保存在xml中的给定文件,但我收到错误"对象引用未设置为对象的实例。"

编辑:我不能使用任何类型的序列化。

1 个答案:

答案 0 :(得分:1)

对于这种情况,最简单的方法是使用XmlSerializer。这不是你可以用.net做的唯一方法,因为有XmlReader,XmlTextReader和XDocument来帮助你,但是XmlSerializer允许你轻松地将数据结构转换为xml并返回。这是一个例子:

     using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml;
    using System.Xml.Serialization;

    namespace TestXmlSerializer
    {
        class Program
        {
            static void Main(string[] args)
            {
                var g = new Group
                {
                    Name="g2",
                    Keys = new[] {
                        new Key { Username="a" },
                        new Key { Password="b" }
                    }
                };

                Group g2;

                var xs = new XmlSerializer(typeof(Group));
                var s = string.Empty;


                using (var tw = new StringWriter()) {
                    using (var xw = XmlWriter.Create(tw))            
                        xs.Serialize(xw, g);               
                    s = tw.ToString();
                }

                Console.WriteLine(s);


                using (var ms = new StringReader(s))
                {               
                    using (var xw = XmlReader.Create(ms))
                        g2 = xs.Deserialize(xw) as Group;
                }

                Console.WriteLine(g2.Name);
            }

        }


        [Serializable]
        public class Key
        {
            [XmlAttribute]
            public string Title;
            [XmlAttribute]
            public string Username;
            [XmlAttribute]
            public string Password;
            [XmlAttribute]
            public string Url;
            [XmlAttribute]
            public string Notes;
        }

        [Serializable]
        public class Group
        {
            [XmlAttribute]
            public string Name;

            [XmlElement]
            public Key[] Keys;
        }
    }