Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deserialize a list from xml without the plural parent element?

I would like to deserialize a HTML table into an object. But with the following code, it expects to see <Rows> as the parent of <tr>'s and <Cells> as the parent of <td>'s. I want to keep this class structure. Am I missing any attribute declaration?

<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; }
}
like image 393
weilin8 Avatar asked Dec 31 '25 05:12

weilin8


1 Answers

Try setting the attributes as shown below. Note that you'll have to change the type of Value on the Cell class from object to 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; }
}
like image 51
rsbarro Avatar answered Jan 02 '26 17:01

rsbarro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!