Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

c# - Deserializing XML File with multiple element attributes - attributes are not deserializing

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);}
   }
}

Now the code to deserialize:

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);
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;}
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...