c# - 序列化数组时如何使用 XmlAttributeOverrides?

标签 c# .net xml-serialization

我有一个名为 _updatedComponents 的数组,其中包含 NetworkComponent 类的对象。我必须以更改根元素 (=array) 的名称和命名空间并将单个 NetworkComponent-item 的名称更改为组件的方式对其进行序列化。我有下面的代码导致异常:

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[] - 这会让事情变得非常棘手。我建议写一个包装器类型:

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

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

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

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

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

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

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

关于c# - 序列化数组时如何使用 XmlAttributeOverrides?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2244486/

相关文章:

c# - MVC 我的网址正在创建 "?Length=4"

c# - 如何从列表框中选择的项目中获取特定属性

c# - 如何计算 asp.net 表单中的复选框

.net - 体面的低占用空间Web服务器? (。网)

.net - 如何判断我的应用程序是否在 RDP session 中运行

c# - 将派生类转换为基类可以在使用泛型时保留派生知识

c# - 何时使用ShouldSerializeXXX和XmlIgnoreAttribute进行XML序列化

c# - 使 C# 程序能够在任何操作系统上编译

c# - 如何通过 XML 序列化抑制命名空间的输出?

c# - 使用 [XmlAnyElement]