2

I have a xml file with following content:

<offer>
    ...
    <date type="Foo">Some value 1</date>
    <date type="Bar">Some value 2</date>
    <date type="Baz">Some value 3</date>
    ...
</offer>

And I have an enumeration like this:

public enum DateType
{
    Foo, Bar, Baz
}

And classes:

public class Date
{
    public DateType Type { get; set; }
    public string Value { get; set; }
}

public class Schedule
{
    ...
    public Date[] Dates { get; set; }
    ...
}

What I need to do that xml can be deserialized in this classes?

P.S. As a result I need Enum values to be mapped in public Date[] Dates { get; set; }.

3
  • 1
    Possible duplicate of How to Deserialize XML document Commented Feb 16, 2018 at 10:02
  • @FaizanRabbani This question is not about that you pointed. Commented Feb 16, 2018 at 10:08
  • Share the code you have written to deserialize? Commented Feb 16, 2018 at 10:11

1 Answer 1

1

Use this classes:

public enum DateType
{
    Foo, Bar, Baz
}

[XmlRoot(ElementName = "date")]
public class Date
{
    [XmlAttribute(AttributeName = "type")]
    public DateType Type { get; set; }

    [XmlText]
    public string Value { get; set; }
}

[XmlRoot(ElementName = "offer")]
public class Offer
{
    [XmlElement(ElementName = "date")]
    public Date[] Dates { get; set; }
}

And deserialize with:

string lsXml = @"<offer>
<date type=""Foo"">Some value 1</date>
<date type=""Bar"">Some value 2</date>
<date type=""Baz"">Some value 3</date>
</offer>";

XmlSerializer loXmlSerializer = new XmlSerializer(typeof(Offer));
var loOffer = loXmlSerializer.Deserialize(new StringReader(lsXml)) as Offer;
foreach (var loDate in loOffer.Dates)
{
    Console.WriteLine($"{loDate.Type}: {loDate.Value}");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.