反序列化具有多个元素属性的 XML 文件 - 属性不会反序列化 [英] Deserializing XML File with multiple element attributes - attributes are not deserializing

查看:33
本文介绍了反序列化具有多个元素属性的 XML 文件 - 属性不会反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 C# .Net 4 -- XML 示例(真实示例有 6 个属性)

Using C# .Net 4 -- XML Sample (Real sample has 6 attributes)

<TestXML>
  <TestElement attr1="MyAttr" attr2="1" DateAdded="">25</TestElement>
</TestXML>

对于我的类定义,我有以下内容:

For my class definition I have the following:

public class TestXML() {
   public TestXML() {}

   public int TestElement {get; set;}
   [XmlAttribute]
   public string attr1 {get; set;}
   [XmlAttribute]
   public string attr2 {get; set;}
   [XmlIgnore]
   public DateTime DateAdded {get; set;}
   [XmlAttribute("DateAdded")]
   public string dateadded {
      get{ return (DateAdded == null ? "" : DateAdded.ToString();}
      set{ if(!value.Equals("")) DateAdded = DateTime.Parse(value);}
   }
}

现在反序列化的代码:

string xml = "<TestXML><TestElement attr1="MyAttr" attr2="1" DateAdded="">26</TestElement></TestXML>"
using (StringReader sr = new StringReader(xml)) {
   XmlSerializer serializer = new XmlSerializer(typeof(TestXML));
   TestXML myxml = (TestXML)serializer.Deserialize(sr);
}

现在我们得到的结果是(在VS中查看对象):

Now the result we get is(viewing object in VS):

myxml
  attr1         |  null
  attr2         |  null
  TestElement   |  25

完全不知道为什么属性不会反序列化.

At a complete loss as to why the attributes will not deserialize.

推荐答案

要做到这一点,您需要两个级别:

To do that you need two levels:

[XmlRoot("TestXML")]
public class TestXml {
    [XmlElement("TestElement")]
    public TestElement TestElement { get; set; }
}

public class TestElement {
    [XmlText]
    public int Value {get;set;}

    [XmlAttribute]
    public string attr1 {get;set;}

    [XmlAttribute]
    public string attr2 {get;set;}
}

注意>26 < 也可能导致问题(空格);你可能需要它是一个字符串而不是一个整数.

Note that the > 26 < may cause problems too (whitespace); you may need that to be a string instead of an int.

这篇关于反序列化具有多个元素属性的 XML 文件 - 属性不会反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆