如何在具有多个根的c#中反序列化XML?

如何在具有多个根的c#中反序列化XML?,c#,xml,list,serialization,C#,Xml,List,Serialization,我有一个“xml”文件,如下所示: <root> <a> <b> </b> </a> </root> <root> <a> <b> </b> </a> </root> <root> <a> <b> </b> </a> </root> .... s

我有一个“xml”文件,如下所示:

<root>
 <a>
  <b>
  </b>
 </a>
</root>
<root>
 <a>
  <b>
  </b>
 </a>
</root>
<root>
 <a>
  <b>
  </b>
 </a>
</root>
....
static public List<CT> DeSerialize(string FileName)
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(List<CT>), new XmlRootAttribute("root"));
        List<CT> result;

        using (FileStream fileStream = new FileStream(@FileName, FileMode.Open))
        {
            result = (List<CT>)deserializer.Deserialize(fileStream);
        }

        return result;
    }

....

它是通过对象列表上的serialize方法创建的。所以我有匹配的类来反序列化它

现在,当我尝试反序列化时,我得到了多个根的错误。 有没有办法再次将此文件反序列化到对象列表中

我的一个想法是围绕列出的类包装另一个类,并将其称为“rootclass”,然后只序列化这个类。这将导致一个单一的根。但是,是否有另外一种方法可以只使用给定的XML文件

我的反序列化如下所示:

<root>
 <a>
  <b>
  </b>
 </a>
</root>
<root>
 <a>
  <b>
  </b>
 </a>
</root>
<root>
 <a>
  <b>
  </b>
 </a>
</root>
....
static public List<CT> DeSerialize(string FileName)
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(List<CT>), new XmlRootAttribute("root"));
        List<CT> result;

        using (FileStream fileStream = new FileStream(@FileName, FileMode.Open))
        {
            result = (List<CT>)deserializer.Deserialize(fileStream);
        }

        return result;
    }
静态公共列表反序列化(字符串文件名)
{
XmlSerializer反序列化器=新的XmlSerializer(typeof(List),新的XmlRootAttribute(“root”);
列出结果;
使用(FileStream FileStream=newfilestream(@FileName,FileMode.Open))
{
结果=(列表)反序列化程序。反序列化(文件流);
}
返回结果;
}

您有片段,因此使用设置为片段的XmlReader:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ConformanceLevel = ConformanceLevel.Fragment;
            XmlReader reader = XmlReader.Create(FILENAME,settings);


            while (!reader.EOF)
            {
                if (reader.Name != "root")
                {
                    reader.ReadToFollowing("root");
                }
                if (!reader.EOF)
                {
                    XElement root = (XElement)XElement.ReadFrom(reader);
                }
            }
        }
    }
}

List
Array
在序列化时创建自己的根对象。为什么不将列表/数组对象传递给序列化程序?在我想将新元素保存到文件的程序生命周期中,您可能会从这篇文章中受益。所以我并不真的想要一个真正的根元素“所以我有一个匹配的类来反序列化它”,正如你allready所说的,在你的例子中没有“根”,因此没有任何东西需要反序列化。这是因为您的xml格式不正确,它假定您只有一个root.element。看起来像的副本。同意吗?