c# – 使用XmlArray反序列化xml文件?

前端之家收集整理的这篇文章主要介绍了c# – 使用XmlArray反序列化xml文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图反序列化这个xml结构.
<?xml version="1.0"?>
<DietPlan>
    <Health>
        <Fruit>Test</Fruit>
        <Fruit>Test</Fruit>
        <Veggie>Test</Veggie>
        <Veggie>Test</Veggie>
    </Health>
</DietPlan>

我试过:

[Serializable]
[XmlRoot(ElementName = "DietPlan")]
public class TestSerialization
{
    [XmlArray("Health")]
    [XmlArrayItem("Fruit")]
    public string[] Fruits { get; set; }

    [XmlArray("Health")]
    [XmlArrayItem("Veggie")]
    public string[] Veggie { get; set; }
}

但是这会抛出一个异常“XML元素已经存在于当前作用域中,使用XML属性为该元素指定另一个XML名称或命名空间.
感谢adv.

解决方法

您需要一个通用类型才能反序列化您的XML,并且您可以使用[XmlElement]命名空间定义根据元素名称实例化的类型,如下所示.
public class StackOverflow_15907357
{
    const string XML = @"<?xml version=""1.0""?>
                        <DietPlan>
                            <Health>
                                <Fruit>Test</Fruit>
                                <Fruit>Test</Fruit>
                                <Veggie>Test</Veggie>
                                <Veggie>Test</Veggie>
                            </Health>
                        </DietPlan>";

    [XmlRoot(ElementName = "DietPlan")]
    public class TestSerialization
    {
        [XmlArray("Health")]
        [XmlArrayItem("Fruit",Type = typeof(Fruit))]
        [XmlArrayItem("Veggie",Type = typeof(Veggie))]
        public Food[] Foods { get; set; }
    }

    [XmlInclude(typeof(Fruit))]
    [XmlInclude(typeof(Veggie))]
    public class Food
    {
        [XmlText]
        public string Text { get; set; }
    }

    public class Fruit : Food { }
    public class Veggie : Food { }

    public static void Test()
    {
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
        XmlSerializer xs = new XmlSerializer(typeof(TestSerialization));
        TestSerialization obj = (TestSerialization)xs.Deserialize(ms);
        foreach (var food in obj.Foods)
        {
            Console.WriteLine("{0}: {1}",food.GetType().Name,food.Text);
        }
    }
}
原文链接:https://www.f2er.com/csharp/94007.html

猜你在找的C#相关文章