C#中的XML序列化数组

7
我很难理解这个问题,我有一个看起来像这样的 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序列化方面非常新手,希望能得到帮助,谢谢。


使用 XmlArray 为 Words 属性。 - sll
1
只是需要注意的一点,如果你正在将XML转换为对象,那就是反序列化。将对象转换为XML(或任何其他可以发送到磁盘或网络流的格式)是序列化。 - MCattle
2个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接