我如何能得到XmlRoot有对象的集合? [英] How do can I get XmlRoot to have a collection of objects?

查看:178
本文介绍了我如何能得到XmlRoot有对象的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何序列化下面的类为XML(以特定的方式,见下文):





<预类=郎-CS prettyprint-覆盖> [XmlRoot(农场)]
公共类农场
{
[XmlArray]
[XmlArrayItem (人的typeof(人))]
[XmlArrayItem(狗的typeof(狗))]
公开名单<动物>动物{搞定;组; }
}



(假设无论从动物导出,并且它们都具有一个名称属性,它装饰有 [XmlAttribute(姓名)]



我需要能够创建该对象:





<预类=郎-CS prettyprint-覆盖> VAR myFarm =新农场
{
组=新的List<动物> {
新的Person {名称=鲍勃},
新狗{名称=菲多}
}
};



...并将其序列化到以下文件:





<预类=郎咸平的XML prettyprint-覆盖> <?XML版本=1.0>?;
<农场及GT;
<人名=鲍勃/>
<狗NAME =菲多/>
< /农场>



但是,当我序列化 myFarm (结果输出到控制台)是这样的:





<预类=郎-CS prettyprint-覆盖> VAR串行=新XmlSerializer的(typeof运算(农场));
变种命名空间=新XmlSerializerNamespaces();
namespaces.Add(,);
serializer.Serialize(System.Console.Out,myFarm,命名空间);



......结果是这样的:





<预类=郎咸平的XML prettyprint-覆盖> <?XML版本=1.0>?;
<农场及GT;
<动物>
<人名=鲍勃/>
<狗NAME =菲多/>
< /动物和GT;
< /农场>



注意额外的不必要的动物元素。我该如何摆脱这件事?更改的XML模式是不是一种选择,但改变代码。我真的只是想能够解决这个问题,我希望一个容易解决的有人知道(或知道一个事实,即没有一个简单的办法)。



感谢


解决方案

使用以下属性,而不是:

  [XmlRoot(农场)] 
公共类农场
{
[XmlElement的(人,typeof运算(人))]
[XmlElement的(狗的typeof(狗))]
公开名单<动物>项目{搞定;组; }
}


I'm trying to figure out how to serialize the following class into XML (in a specific way, see below):

[XmlRoot("Farm")]
public class Farm
{
    [XmlArray]
    [XmlArrayItem("Person", typeof(Person))]
    [XmlArrayItem("Dog", typeof(Dog))]
    public List<Animal> Animals { get; set; }
}

(Assume that Dog and Person both derive from Animal, and they both have a Name property which is decorated with [XmlAttribute("Name")].)

I need to be able to create this object:

var myFarm = new Farm
{
    Animals = new List<Animal> { 
        new Person { Name = "Bob" },  
        new Dog { Name = "Fido" }
    }
};

...and have it serialize to the following document:

<?xml version="1.0"?>
<Farm>
    <Person Name="Bob"/>
    <Dog Name="Fido"/>
</Farm>

But, when I serialize myFarm (result outputs to console) like this:

var serializer = new XmlSerializer(typeof(Farm));
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("", "");
serializer.Serialize(System.Console.Out, myFarm, namespaces);

...the result is this:

<?xml version="1.0"?>
<Farm>
    <Animals>
        <Person Name="Bob"/>
        <Dog Name="Fido"/>
    </Animals>
</Farm>

Notice the extra unwanted Animals element. How do I get rid of this? Changing the XML schema is not an option, but changing the code is. I'd really just like to be able to get around this problem and am hoping someone knows of an easy fix (or knows for a fact that there is not an easy fix).

Thanks!

解决方案

Use the following attributes instead:

[XmlRoot("Farm")]
public class Farm
{
    [XmlElement("Person", typeof(Person))]
    [XmlElement("Dog", typeof(Dog))]
    public List<Animal> Items { get; set; }
}

这篇关于我如何能得到XmlRoot有对象的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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