2012-03-08 11 views
8

Tengo un List<> que he logrado escribir en el archivo. Ahora estoy tratando de leer el mismo archivo y escribirlo nuevamente en List<>. ¿Hay algún método para hacerlo? ¿Alguien puede ayudarme con el comienzo? ¿Será útil?¿Cómo leer un archivo XML y escribir en la Lista <>?

+0

http://stackoverflow.com/questions/670563/linq-to-read-xml similares cuestión, podría u echar un vistazo – AnarchistGeek

+0

Prueba este http://stackoverflow.com/questions/4084393/how-to-read-xml-file-to-a-dictionarystring-liststring-with-empty-strings- para – PraveenVenu

Respuesta

9

Creo que la forma más sencilla es utilizar el 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); 
} 
4

puede usar LINQ to XML para leer su archivo XML y vincularlo a su Lista.

http://www.mssqltips.com/sqlservertip/1524/reading-xml-documents-using-linq-to-xml/ este enlace tiene suficiente información al respecto.

esto es algo que hice en el pasado; Espero que ayude. Creo que quiere exactamente lo mismo

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

Una forma fácil es

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(); 


    } 
} 
7

puede probar esta (usando System.Xml.Linq)

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

Estoy de acuerdo en usar Linq para XML, pero seguí estos ejemplos http://www.dotnetcurry.com/linq/564/linq-to-xm l-tutoriales-ejemplos. – Caverman

0

Si está trabajando con el patrón Singleton, ¡aquí le mostramos cómo leer XML en él!

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

Esto abre la accesibilidad ABM, la actualización es un poco complicado de lo que se escribe en el 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")); 
     } 
    } 
Cuestiones relacionadas