简体   繁体   English

XmlSerializer和类和xml属性中的不同字段

[英]XmlSerializer and different field in class and xml attribute

I have xml with several items, for example: 我有几个项目的xml,例如:

<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<TestClass>));
List<TestClass> list = (List<TestClass>)s.Deserialize("myXml.xml");

After it I get list with objects TestClass, but property Element didn't set. 之后,我得到带有对象TestClass的列表,但未设置属性Element。 How I must change serialization, if I want to set TestElement2 in Element field? 如果要在“元素”字段中设置TestElement2,如何更改序列化?

You need to decorate the Element property with an [XmlElement] attribute: 您需要使用[XmlElement]属性装饰Element属性:

[XmlRoot("TestObject")]
class TestClass {
    public int TestElement1 { get; set; }

    [XmlElement("TestElement2")]
    public int Element { get; set; }
}

Try XmlElement attribute 尝试XmlElement属性

public class TaxRates{
    [XmlElement(ElementName = "TaxRate")]
    public decimal ReturnTaxRate;
}

see Controlling XML Serialization Using Attributes 请参阅使用属性控制XML序列化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM