[英]c# Linq to XML load List in object
I would like save and Load this Class in XML with Linq:我想用 Linq 在 XML 中保存和加载这个类:
public class AssemblyVerwaltung
{
public string AssemblyName;
public List<string> List_KlassenNamen;
}
In Form1 i have a List of this Class:在 Form1 中,我有一个此类的列表:
List<AssemblyVerwaltung> List_AssemblyVerwaltung;
The Save mehtode looks like that保存方法看起来像这样
void Save(XMLPath)
{
//need help hear
//Save List of "AssemblyVerwaltung" with Linq to XML
}
and the Load Mehtode looks like that Load Mehtode 看起来像那样
void LoadXML(XMLPath)
{
List_AssemblyVerwaltung = //need help hear (load XML with Linq)
}
You can have only one root node in XML. XML 中只能有一个根节点。 So you have to wrap the code with a Root Element.
所以你必须用一个根元素来包装代码。 Try code below
试试下面的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication34
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
List<AssemblyVerwaltung> List_AssemblyVerwaltung = new List<AssemblyVerwaltung>();
Root root = new Root();
root.List_AssemblyVerwaltung = new List<AssemblyVerwaltung>(List_AssemblyVerwaltung);
XmlSerializer serializer = new XmlSerializer(typeof(Root));
StreamWriter writer = new StreamWriter(FILENAME);
XmlSerializerNamespaces _ns = new XmlSerializerNamespaces();
_ns.Add("", "");
serializer.Serialize(writer, root, _ns);
writer.Flush();
writer.Close();
writer.Dispose();
XmlSerializer xs = new XmlSerializer(typeof(Root));
XmlTextReader reader = new XmlTextReader(FILENAME);
Root newRoot = (Root)xs.Deserialize(reader);
}
}
[XmlRoot("Root")]
public class Root
{
[XmlElement("List_AssemblyVerwaltung")]
public List<AssemblyVerwaltung> List_AssemblyVerwaltung { get; set; }
}
[XmlRoot("List_AssemblyVerwaltung")]
public class AssemblyVerwaltung
{
[XmlElement("AssemblyName")]
public string AssemblyName {get;set;}
[XmlElement("List_KlassenNamen")]
public List<string> List_KlassenNamen {get;set;}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.