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 序列化真的很陌生,任何帮助将不胜感激

4

2 回答 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; }
}
于 2012-05-24T18:30:20.347 回答
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();
于 2012-05-24T18:26:27.363 回答