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

后端 未结 4 2089
你的背包
你的背包 2020-12-09 16:40

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


  25

        
相关标签:
4条回答
  • 2020-12-09 17:07

    I just ran a test serializing/deserializing your object and it seems to work fine

    Test:

    TestXML obj = new TestXML{ attr1 = "Attrib1", attr2 = "Attrib2", DateAdded = DateTime.Now, TestElement = 44};
    
    XmlSerializer serializer = new XmlSerializer(typeof(TestXML));
    using (FileStream stream = new FileStream(@"C:\StackOverflow.xml", FileMode.OpenOrCreate))
    {
        serializer.Serialize(stream, obj);
    }
    
    using (FileStream stream = new FileStream(@"C:\StackOverflow.xml", FileMode.Open))
    {
        TestXML myxml = (TestXML)serializer.Deserialize(stream);
    }
    

    all attributes deserialized ok.

    Result:

    enter image description here

    Xml:

    <?xml version="1.0"?>
    <TestXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" attr1="Attrib1" attr2="Attrib2" DateAdded="10/01/2013 9:46:23 a.m.">
      <TestElement>44</TestElement>
    </TestXML>
    
    0 讨论(0)
  • 2020-12-09 17:08

    You are defining the attributes on TestElement while they should be on TestXML. Example:

    @"<TestXML attr1=""MyAttr"" attr2=""1"">
          <TestElement>26</TestElement>
      </TestXML>"
    
    0 讨论(0)
  • 2020-12-09 17:11

    As an additional note to the accepted answer. Make sure the xml element doesn't contain a nil="true" attribute like this:

    <TestXML>
      <TestElement attr1="MyAttr" attr2="1" DateAdded="" xsi:nil="true">25</TestElement>
    </TestXML>
    

    From my experience the deserializer won't deserialize attributes of an element marked as null (nil).

    0 讨论(0)
  • 2020-12-09 17:12

    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.

    0 讨论(0)
提交回复
热议问题