如何将XML文件读入List<>?

13

我有一个写入XML文件的 List<>。 现在,我正在尝试读取相同的文件并将其写回到 List<> 中。 是否有一种方法可以实现这个?


类似的问题,您能看一下这个链接吗?它涉及到使用LINQ读取XML。 - AnarchistGeek
尝试这个链接:https://dev59.com/AlHTa4cB1Zd3GeqPS5hM - PraveenVenu
5个回答

19

我认为最简单的方法是使用 XmlSerializer

XmlSerializer serializer = new XmlSerializer(typeof(List<MyClass>));

using(FileStream stream = File.OpenWrite("filename"))
{
    List<MyClass> list = new List<MyClass>();
    serializer.Serialize(stream, list);
}

using(FileStream stream = File.OpenRead("filename"))
{
    List<MyClass> dezerializedList = (List<MyClass>)serializer.Deserialize(stream);
}

10

你可以尝试这个方法(使用 System.Xml.Linq)

XDocument xmlDoc = XDocument.Load("yourXMLFile.xml");
var list = xmlDoc.Root.Elements("id")
                           .Select(element => element.Value)
                           .ToList();

同意使用 Linq to XML,但我按照这些示例进行操作:http://www.dotnetcurry.com/linq/564/linq-to-xml-tutorials-examples。 - Caverman

5
您可以使用LINQ to XML读取XML文件并将其绑定到列表中。以下链接有关于此的足够信息:http://www.mssqltips.com/sqlservertip/1524/reading-xml-documents-using-linq-to-xml/。这是我过去做过的事情,希望能对您有所帮助。我认为您想要做的就是完全相同的事情。
    public static List<ProjectMap> MapInfo()
     {

         var maps = from c in XElement.Load(System.Web.Hosting.HostingEnvironment.MapPath("/ProjectMap.xml")).Elements("ProjectMap")
                     select c;
         List<ProjectMap> mapList = new List<ProjectMap>();

         foreach (var item in maps)
         {
             mapList.Add(new ProjectMap() { Project = item.Element("Project").Value, SubProject = item.Element("SubProject").Value, Prefix = item.Element("Prefix").Value, TableID = item.Element("TableID").Value  });

         }
         return mapList;
    }

4
一种简单的方法是:
using System;
using System.Linq;
using System.Xml.Linq;

public class Test
{
    static void Main()
    {
        string xml = "<Ids><id>1</id><id>2</id></Ids>";

        XDocument doc = XDocument.Parse(xml);

        List<string> list = doc.Root.Elements("id")
                           .Select(element => element.Value)
                           .ToList();


    }
}

1
如果您正在使用单例模式,以下是将XML读入其中的方法!
public static GenericList Instance {

        get {

                XElement xelement = XElement.Load(HostingEnvironment.MapPath("RelativeFilepath"));
                IEnumerable<XElement> items = xelement.Elements();
                instance = new GenericList();
                instance.genericList = new List<GenericItem>{ };

                foreach (var item in items) {

                    //Get the value of XML fields here
                    int _id = int.Parse(item.Element("id").Value);
                    string _name = item.Element("name").Value;

                    instance.genericList.Add(
                                  new GenericItem() {

                                      //Load data into your object
                                      id = _id,
                                      name = _name
                                  });   
                    }
            return instance;
        }
    }

这使得CRUD操作变得更加便捷,更新操作有些棘手,因为它会写入XML。
    public void Save() {

        XDocument xDoc = new XDocument(new XDeclaration("Version", "Unicode type", null));
        XElement root = new XElement("GenericList");
        //For this example we are using a Schema to validate our XML
        XmlSchemaSet schemas = new XmlSchemaSet();
        schemas.Add("", HostingEnvironment.MapPath("RelativeFilepath"));

        foreach (GenericItem item in genericList) {

            root.Add(
                //Assuming XML has a structure as such
                //<GenericItem>
                //  <name></name>
                //  <id></id>
                //</GenericItem>

                new XElement("GenericItem",                        
                        new XElement("name", item.name),
                        new XElement("id", item.id)
                ));
        }
        xDoc.Add(root);

        //This is where the mentioned schema validation takes place
        string errors = "";
        xDoc.Validate(schemas, (obj, err) => {
            errors += err.Message + "/n";
        });

        StringWriter writer = new StringWriter();
        XmlWriter xWrite = XmlWriter.Create(writer);
        xDoc.Save(xWrite);
        xWrite.Close();

        if (errors == "")
        {
            xDoc.Save(HostingEnvironment.MapPath("RelativeFilepath"));
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接