2012-05-24 16 views
7

Tengo problemas para calcular esto, tengo una hoja de XML que tiene este aspectoXML gama de serialización en C#

<root> 
    <list id="1" title="One"> 
    <word>TEST1</word> 
    <word>TEST2</word> 
    <word>TEST3</word> 
    <word>TEST4</word> 
    <word>TEST5</word> 
    <word>TEST6</word> 
    </list> 
    <list id="2" title="Two"> 
    <word>TEST1</word> 
    <word>TEST2</word> 
    <word>TEST3</word> 
    <word>TEST4</word> 
    <word>TEST5</word> 
    <word>TEST6</word> 
    </list> 
</root> 

y estoy tratando de serializar en

public class Items 
{ 
    [XmlAttribute("id")] 
    public string ID { get; set; } 

    [XmlAttribute("title")] 
    public string Title { get; set; } 

    //I don't know what to do for this 
    [Xml... something] 
    public list<string> Words { get; set; } 
} 

//I don't this this is right either 
[XmlRoot("root")] 
public class Lists 
{ 
    [XmlArray("list")] 
    [XmlArrayItem("word")] 
    public List<Items> Get { get; set; } 
} 

//Deserialize XML to Lists Class 
using (Stream s = File.OpenRead("myfile.xml")) 
{ 
    Lists myLists = (Lists) new XmlSerializer(typeof (Lists)).Deserialize(s); 
} 

I Soy realmente nuevo con la serialización de XML y XML, cualquier ayuda sería muy apreciada

+0

Uso XmlArray de propiedad Words – sll

+1

Solo un punto a tener en cuenta, si está convirtiendo XML en objetos, eso es Deserializar. La conversión de objetos a XML (o cualquier otro formato que pueda enviarse a un disco o red steam) se está serializando. – MCattle

Respuesta

8

que debería funcionar si declara sus clases como

public class Items 
{ 
    [XmlAttribute("id")] 
    public string ID { get; set; } 

    [XmlAttribute("title")] 
    public string Title { get; set; } 

    [XmlElement("word")] 
    public List<string> Words { get; set; } 
} 

[XmlRoot("root")] 
public class Lists 
{ 
    [XmlElement("list")] 
    public List<Items> Get { get; set; } 
} 
3

Si solo necesita leer su XML en una estructura de objetos, podría ser más fácil usar XLINQ.

definir la clase de este modo:

public class WordList 
{ 
    public string ID { get; set; } 
    public string Title { get; set; } 
    public List<string> Words { get; set; } 
} 

y después lee el XML:

XDocument xDocument = XDocument.Load("myfile.xml"); 

List<WordList> wordLists = 
(
    from listElement in xDocument.Root.Elements("list") 
    select new WordList 
    { 
     ID = listElement.Attribute("id").Value, 
     Title = listElement.Attribute("title").Value, 
     Words = 
     (
      from wordElement in listElement.Elements("word") 
      select wordElement.Value 
     ).ToList() 
    } 
).ToList();