【问题标题】:XML serialization array in C#C#中的XML序列化数组
【发布时间】:2012-05-24 18:13:49
【问题描述】:

我无法解决这个问题,我有一个看起来像这样的 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 序列化的新手,非常感谢任何帮助

【问题讨论】:

  • 对 Words 属性使用 XmlArray
  • 请注意,如果您要将 XML 转换为对象,那就是反序列化。将对象转换为 XML(或任何其他可以发送到磁盘或网络流的格式)正在序列化。

标签: c# .net xml


【解决方案1】:

如果您将类声明为,它应该可以工作

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

【讨论】:

    【解决方案2】:

    如果您只是需要将 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();
    

    【讨论】:

      猜你喜欢
      • 2010-09-12
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 2020-01-31
      • 2016-04-13
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      相关资源
      最近更新 更多