0

i have part of xml document

<Tender SubTenderType="BC" TenderType="Check">
   <TenderTotal>
      <Amount>10.00</Amount>
   </TenderTotal>
</Tender>

i need convert it to class.

public class Tender
{
    public string SubTenderType { get; set; } 
    public string TenderType { get; set; }
    public decimal Amount { get; set; }
}

what i already wrote and this work. but i interseing can i deserialize xml to class as written above?

[Serializable]
public class Tender
{
    [XmlAttribute("SubTenderType")]
    public string SubTenderType { get; set; }       

    [XmlAttribute("TenderType")]
    public string TenderType { get; set; }      

    [XmlElement("TenderTotal")]
    public TenderTotal TenderTotal { get; set; }
}

[Serializable]
public class TenderTotal
{
    [XmlElement("Amount")]
    public decimal Amount { get; set; }
}
mi4man
  • 3
  • 2
  • Possible duplicate of [How to deserialize xml to object](https://stackoverflow.com/questions/10518372/how-to-deserialize-xml-to-object) – OlegI Sep 19 '17 at 13:24
  • There are a lot of existed answers available https://stackoverflow.com/questions/10518372/how-to-deserialize-xml-to-object https://stackoverflow.com/questions/364253/how-to-deserialize-xml-document – OlegI Sep 19 '17 at 13:26
  • @OlegI it is not duplicate – mi4man Sep 19 '17 at 13:27
  • @OlegI maybe i wrong ask. i want remove class TenderTotal. and deserialize xml to class "class Tender { public string SubTenderType { get; set; } public string TenderType { get; set; } public decimal Amount { get; set; } }" – mi4man Sep 19 '17 at 13:28

2 Answers2

0

You can deserialize xml to first Type "Tender" and next use autoMapper to map your type (create new object of different type)

create map:

config.CreateMap<TenderFirst, TenderSecond>().ForMember(x => x.TenderTotal.Amount, y => y.Amount ())
0

Having the following class without XmlAttribute:

public class Tender
{
    public string SubTenderType { get; set; } 
    public string TenderType { get; set; }
    public decimal Amount { get; set; }
}

You can use the XmlAttributeOverrides class to override the behavior of the serializer in such a way that instead of elements it would do the attributes.

var attrSTT = new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("SubTenderType") };
var attrTT = new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("TenderType") };

var overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Tender), nameof(Tender.SubTenderType), attrSTT);
overrides.Add(typeof(Tender), nameof(Tender.TenderType), attrTT);

var xs = new XmlSerializer(typeof(Tender), overrides);

However, in this way impossible add a new item or wrap one element in another.


Therefore, you have to do custom serialization, or map one type to another, or writing a custom xml reader/writer, or perform the read/write manually (for example, using linq2xml). There are many ways...

Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49