1

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; }
}
Tito
  • 663
  • 1
  • 8
  • 14
  • please check this answer https://stackoverflow.com/questions/43109646/converting-xml-to-c-sharp-object/43109813#43109813 – Hüseyin Burak Karadag Feb 13 '18 at 05:36
  • Hüseyin BurakKaradag, I can't find anything over there. There's straight one to one mapping between nodes and properties. – Tito Feb 13 '18 at 05:48
  • Looks like a duplicate of [C# Get all text from xml node including xml markup using Visual studio generated class](https://stackoverflow.com/q/40715261/3744182) and [How to get an XML node value as string when deserializing](https://stackoverflow.com/q/47719672/3744182). – dbc Feb 13 '18 at 05:59
  • Demo of the solution from [C# Get all text from xml node including xml markup using Visual studio generated class](https://stackoverflow.com/q/40715261/3744182): https://dotnetfiddle.net/5i01Uc – dbc Feb 13 '18 at 06:12

0 Answers0