2012-05-24 14 views
7

Mam problemy ze zorientowaniem na to uwagę, mam arkusz xml, który wygląda takXML w 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> 

I staram się szeregować je w

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 "Naprawdę nowy z serializacją XML i XML, każda pomoc byłaby bardzo ceniona

+0

Korzystanie XmlArray nieruchomości Words – sll

+1

Wystarczy zwrócić uwagę, jeśli konwertujesz XML na obiekty, to jest Deserializowanie. Konwersja obiektów do formatu XML (lub dowolnego innego formatu, który może być wysłany na dysk lub sieć wodną) jest serializowana. – MCattle

Odpowiedz

8

To powinno działać, jeśli deklarują swoje klasy jako

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

Jeśli potrzebujesz tylko do odczytu XML do struktury obiektu, może być łatwiej używać XLINQ.

Zdefiniuj klasę tak:

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

A następnie odczytać 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();