2012-05-24 71 views
7

我无法搞清楚了这一点,我有一个XML纸张看起来像这样XML序列化阵列

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

而且我想它序列化到

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

我对XML和XML序列化来说真的很新,任何帮助都将不胜感激

+0

使用XmlArray的单词属性它应该工作 – sll

+1

只需注意一点,如果您将XML转换为对象,那就是反序列化。将对象转换为XML(或可以发送到磁盘或网络蒸汽的任何其他格式)是序列化。 – MCattle

回答

8

如果你声明你的类作为

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

如果您只需将XML读入对象结构中,则可能更容易使用XLINQ。

定义类,像这样:

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

然后读取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();