【问题标题】:How do I deserialize a list from xml without the plural parent element?如何在没有复数父元素的情况下从 xml 反序列化列表?
【发布时间】:2011-12-08 03:56:04
【问题描述】:

我想将一个 HTML 表格反序列化为一个对象。但是使用下面的代码,它希望看到<Rows> 是<tr> 的父级,而<Cells> 是<td> 的父级。我想保持这种班级结构。我是否缺少任何属性声明?

<table>
  <tr>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
  </tr>
</table>

public class Table
{
    [XmlArrayItem("tr")]
    public List<Row> Rows { get; set; }
}

public class Row
{
    [XmlArrayItem("td")]
    public List<Cell> Cells { get; set; }
}

public class Cell
{
    public object Value { get; set; }
}

【问题讨论】:

标签: c# xml-serialization


【解决方案1】:

尝试如下设置属性。请注意,您必须将 Cell 类上的 Value 类型从 object 更改为 string。

[XmlRoot("table")]
public class Table
{
    [XmlElement(typeof(Row), ElementName = "tr")]
    public List<Row> Rows { get; set; }
}

public class Row
{
    [XmlElement(typeof(Cell), ElementName = "td")]
    public List<Cell> Cells { get; set; }
}

public class Cell
{
    [XmlText(typeof(string))]
    public string Value { get; set; }
}

【讨论】:

  • 谢谢。这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2017-02-20
  • 2019-12-21
  • 2018-06-28
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
相关资源
最近更新 更多