简体   繁体   中英

xml de-serialization with a very simple file

I just started with xml serialization and I tried these:

(1) throws an exception while deserializing. (2) also throws an exception (3) not working as it should be.

Any ideas is much appreciated. Thanks in advance.

  1) const string XML = @"<?xml version=""1.0""?>
                    <DietPlan>
                            <Fruit>fig</Fruit>
                            <Veggie>Carrot</Veggie>
                    </DietPlan>";

    [XmlRoot(ElementName = "DietPlan")]
    public class TestData
    {
        [XmlElement("Fruit")]
        public XmlElement Fruits { get; set; }

        [XmlElement("Veggie")]
        public XmlElement test { get; set; }  

    }



 2) const string XML = @"<?xml version=""1.0""?>
                    <DietPlan>
                            <Fruit>fig</Fruit>
                            <Fruit>fig</Fruit>
                            <Veggie>Carrot</Veggie>
                            <Veggie>Carrot</Veggie>
                    </DietPlan>";

    [XmlRoot(ElementName = "DietPlan")]
    public class TestData
    {
        [XmlElement("Fruit")]
        public List<XmlElement> Fruits { get; set; }

        [XmlElement("Veggie")]
        public List<XmlElement> test { get; set; }  

    }


3) const string XML = @"<?xml version=""1.0""?>
                    <DietPlan>
                        <Data>
                            <Fruit>fig</Fruit>
                            <Fruit>fig</Fruit>
                            <Veggie>Carrot</Veggie>
                            <Veggie>Carrot</Veggie>
                        </Data>
                    </DietPlan>";

    [XmlRoot(ElementName = "DietPlan")]
    public class TestData
    {
        public Datas Datas { get; set; }

    }

public class Datas
{
    [XmlElement("Fruit")]
    public List<XmlElement> Fruits { get; set; }

    [XmlElement("Veggie")]
    public List<XmlElement> test { get; set; }  
}

1) The xml files are valid in my context! (though not on the correct format)

2) this is the code i use to de-serialize!

public static void Deserialize()
    {
        var ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
        var xs = new XmlSerializer(typeof(TestData));
        var obj = (TestData)xs.Deserialize(ms);

    }

EDIT: (3) already has an answer here enter link description here

If you do not need your class members to be of type XMLElement, use string instead:

[XmlRoot(ElementName = "DietPlan")]
public class TestData
{
    [XmlElement("Fruit")]
    public string Fruits { get; set; }

    [XmlElement("Veggie")]
    public string test { get; set; }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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