I'm very new to .NET, I need to Serialize an XML to object.
How can I write Field.cs
so that it can be serialized for the following XML?
<root>
<field name="title">
<value>Title 1</value>
</field>
<field name="body">
<value>
<div>
Nested HTML markups with all possible elements.
<p> A para here</p>
<a href="#">A link here</a>
<section>any possible html elements</section>
</div>
</value>
</field>
</root>
Here's what i've done so far:
[XmlRoot(ElementName = "field")]
public class Field
{
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "value")]
public string Value { get; set; }
}
This only serialized first item(title). So how can I define Value property so that it can contain anything?
P.S. I do not need to access div
, p
,a
etc as objects inside Field
object. Rather anything inside <value>
be stored as string
would be just fine.
I found the answer I was looking for.
[XmlRoot(ElementName = "field")]
public class Field
{
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "value")]
public Value Value { get; set; }
}
[XmlRoot(ElementName = "value")]
public class Value
{
[XmlAnyElement]
[XmlText]
public XmlNode[] Nodes { get; set; }
}