序列化数组时如何使用XmlAttributeOverrides? [英] how to use XmlAttributeOverrides when serializing an array?

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

问题描述

我有一个名为_updatedComponents的数组,这些数组属于NetworkComponent类的对象.我必须以更改根元素(= array)的名称和名称空间以及将单个NetworkComponent-item的名称更改为component的方式对其进行序列化.我下面有一个代码会导致异常:

I have an array called _updatedComponents of objects that are of class NetworkComponent. I have to serialize it in the way that the name and namespace of the root element (=array) is changed and individual NetworkComponent-item's name is changed to component. I have a code below that causes an exception:

System.InvalidOperationException:出现错误,反映了类型'ComponentSyncService.NetworkComponent []'.---> System.InvalidOperationException:可能未为ComponentSyncService.NetworkComponent []类型指定XmlRoot和XmlType属性.

System.InvalidOperationException: There was an error reflecting type 'ComponentSyncService.NetworkComponent[]'. ---> System.InvalidOperationException: XmlRoot and XmlType attributes may not be specified for the type ComponentSyncService.NetworkComponent[].

代码:

XmlAttributeOverrides xaos = new XmlAttributeOverrides();

// the array itself aka the root. change name and namespace
XmlElementAttribute xea = new XmlElementAttribute(_updatedComponents.GetType());
xea.Namespace = "http://www.example.com/nis/componentsync";
xea.ElementName = "components";

XmlAttributes xas = new XmlAttributes();
xas.XmlElements.Add(xea);
xaos.Add(_updatedComponents.GetType(), xas); 

// then the items of the array. just change the name
xea = new XmlElementAttribute(typeof(networkcomponent));
xea.ElementName = "component";

xas = new XmlAttributes();
xas.XmlElements.Add(xea);
xaos.Add(typeof(NetworkComponent), "NetworkComponent", xas);

XmlSerializer serializer = new XmlSerializer(_updatedComponents.GetType(), xaos);

XmlTextWriter writer = new XmlTextWriter(string.Format("{0}\\ComponentSyncWS_{1}.xml", 
                      Preferences.FileSyncDirectory, requestId), Encoding.UTF8);
serializer.Serialize(writer, _updatedComponents);

推荐答案

什么是 _updatedComponents ?我猜它是一个 NetworkComponent [] -这会使事情变得非常棘手.我建议写一个包装类型:

What is _updatedComponents ? I'm guessing it is a NetworkComponent[] - which will make things very tricky. I would suggest writing a wrapper type:

public class ComponentsMessage {
    public NetworkComponent[] Components {get;set;}
}

然后,您可以关联正确的属性.如果您需要在 NetworkComponent 上支持临时属性,则仍然需要使用属性覆盖(因此,我根本没有修饰上面的内容),但是要使用 ComponentsMessage 应该很高兴接受这些属性.

Then you can associate the correct attributes. If you need to support ad-hoc attributes on NetworkComponent you'd still need to use attribute-overrides (hence I haven't decorated the above at all), but ComponentsMessage should be happy to take the attributes.

或者,只需编写一个单独的DTO并映射值.

Alternately, just write a separate DTO and map the values.

如果很简单,您也许可以使用:

If it is simple, you might just be able to use:

[XmlRoot("components", Namespace = XmlNamespace)]
[XmlType("components", Namespace = XmlNamespace)]
public class ComponentsMessage
{
    public const string XmlNamespace = "http://www.example.com/nis/componentsync";
    [XmlElement("component")]
    public NetworkComponent[] Components { get; set; }
}

或者,如果您必须使用属性覆盖,则我仍将使用包装器对象:

Alternatively, if you must use attribute-overrides, I'd still use a wrapper object:

public class ComponentsMessage
{
    public NetworkComponent[] Components { get; set; }
}
class Program
{
    static void Main()
    {
        NetworkComponent[] _updatedComponents = new NetworkComponent[2] {
            new NetworkComponent{},new NetworkComponent{}
        };
        const string XmlNamespace = "http://www.example.com/nis/componentsync";
        XmlAttributeOverrides ao = new XmlAttributeOverrides();
        ao.Add(typeof(ComponentsMessage), new XmlAttributes {
            XmlRoot = new XmlRootAttribute("components") { Namespace = XmlNamespace },
            XmlType = new XmlTypeAttribute("components") { Namespace = XmlNamespace }
        });
        ao.Add(typeof(ComponentsMessage), "Components", new XmlAttributes {
            XmlElements =  {
                new XmlElementAttribute("component")
            }
        });
        ComponentsMessage msg = new ComponentsMessage { Components = _updatedComponents };
        XmlSerializer serializer = new XmlSerializer(msg.GetType(), ao);
        serializer.Serialize(Console.Out, msg);
    }
}

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

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