如何读取XML文件并写入List<>?

时间:2012-03-08 14:36:54

标签: c# xml

我有List<>我已设法写入文件。 现在我正在尝试读取同一个文件并将其写回List<>。 有没有办法做到这一点? 任何人都可以帮我开始吗? 会有用吗?

5 个答案:

答案 0 :(得分:9)

我认为最简单的方法是使用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);
}

答案 1 :(得分:7)

您可以尝试此操作(使用System.Xml.Linq)

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

答案 2 :(得分:5)

您可以使用LINQ to XML读取XML文件并将其绑定到List。

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

答案 3 :(得分: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();


    }
}

答案 4 :(得分:0)

如果您正在使用Singleton模式,那么就是如何将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"));
        }
    }