XmlSerializer and different field in class and xml attribute
I have xml with several items, for example:
<TestObject>
<TestElement1/>
<TestElement2/>
</TestObject>
<TestObject>
<TestElement1/>
<TestElement2/>
</TestObject>
Also I have class:
class TestClass {
public int TestElement1 { get; set; }
public int Element { get; set; }
}
If I do:
XmlSerializer s = new XmlSerializer(typeof(List<Te开发者_运维百科stClass>));
List<TestClass> list = (List<TestClass>)s.Deserialize("myXml.xml");
After it I get list with objects TestClass, but property Element didn't set. How I must change serialization, if I want to set TestElement2 in Element field?
You need to decorate the Element
property with an [XmlElement]
attribute:
[XmlRoot("TestObject")]
class TestClass {
public int TestElement1 { get; set; }
[XmlElement("TestElement2")]
public int Element { get; set; }
}
Try XmlElement attribute
public class TaxRates{
[XmlElement(ElementName = "TaxRate")]
public decimal ReturnTaxRate;
}
see Controlling XML Serialization Using Attributes
精彩评论