xml文件的使用XmlArray反序列化? [英] Deserialization of xml file by using XmlArray?

查看:162
本文介绍了xml文件的使用XmlArray反序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想反序列化这个XML结构。

I am trying to deserialize this xml structure.

<?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元素已经present在目前的范围内,使用XML属性来指定其他XML名称或命名空间的元素。 由于在副词。

But this throws an exception "The XML element is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element." Thanks in adv.

推荐答案

您需要一个共同的类型,以便能够反序列化XML,并与您可以用 [的XmlElement] 什么类型取决于元素的名称来实例化,如下所示的命名空间。

You need a common type to be able to deserialize your XML, and with that you can define with the [XmlElement] namespace what type to instantiate depending on the name of the element, as shown below.

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

这篇关于xml文件的使用XmlArray反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆