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

标签 c# .net xml xmlserializer

我有几个项目的 xml,例如:

<TestObject>
  <TestElement1/>
  <TestElement2/>
</TestObject>
<TestObject>
  <TestElement1/>
  <TestElement2/>
</TestObject>

我还有课:

class TestClass {
  public int TestElement1 { get; set; }
  public int Element { get; set; }
}

如果我这样做:

XmlSerializer s = new XmlSerializer(typeof(List<TestClass>));
List<TestClass> list = (List<TestClass>)s.Deserialize("myXml.xml");

之后,我得到了包含对象 TestClass 的列表,但是属性 Element 没有设置。如果我想在 Element 字段中设置 TestElement2,我必须如何更改序列化?

最佳答案

您需要使用 [XmlElement] 属性装饰 Element 属性:

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

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

关于c# - XmlSerializer 和类和 xml 属性中的不同字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7593725/

相关文章:

c# - 使用 Windows 窗体移植旧的 Flash 游戏 - 如何嵌入 Flash Player dll?

.net - Windows 每秒多久进行一次线程切换?

c# - 如何始终显示 float 的小数点?

c# - XDocument 对不为空的对象的空引用

c# - 将 URL 添加到 .NET XML 注释

c# - 比较两个列表

c# - Identity Column 的 Int32 限制

c# - 在 LINQ 中分组

c# - 使用 DirectorySearcher API 读取/处理大量数据

c# - WCF 删除 xmlns :tem ="http://tempuri.org/"