0

我刚开始使用 xml 序列化,我尝试了这些:

(1) 反序列化时抛出异常。(2) 还会引发异常 (3) 无法正常工作。

任何想法都非常感谢。提前致谢。

  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) xml 文件在我的上下文中有效!(虽然格式不正确)

2)这是我用来反序列化的代码!

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

    }

编辑:(3)已经有答案在这里输入链接描述

4

1 回答 1

0

如果您不需要您的类成员是 XMLElement 类型,请改用字符串:

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

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

}
于 2013-08-01T07:15:39.640 回答