How to read a XML file and write into List<>?

后端 未结 5 1436
自闭症患者
自闭症患者 2020-12-09 05:09

I have a List<> which I have managed to write into file. Now I am trying to read the same file and write it back to List<>. Is there a

相关标签:
5条回答
  • 2020-12-09 05:33

    I think the easiest way is to use the 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);
    }
    
    0 讨论(0)
  • 2020-12-09 05:42

    An easy way is

    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();
    
    
        }
    }
    
    0 讨论(0)
  • 2020-12-09 05:47

    You can try this (using System.Xml.Linq)

    XDocument xmlDoc = XDocument.Load("yourXMLFile.xml");
    var list = xmlDoc.Root.Elements("id")
                               .Select(element => element.Value)
                               .ToList();
    
    0 讨论(0)
  • 2020-12-09 05:51

    you can use LINQ to XML to read your XML file and bind it to your List.

    http://www.mssqltips.com/sqlservertip/1524/reading-xml-documents-using-linq-to-xml/ this link has enough info about it.

    this is something I did in past; I hope it helps. I think you want to exactly same thing

        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;
        }
    
    0 讨论(0)
  • 2020-12-09 05:53

    If you're working with the Singleton pattern, here's how to read XML into it!

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

    This opens up CRUD accessibility, update is kinda of tricky as it writes to the 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"));
            }
        }
    
    0 讨论(0)
提交回复
热议问题