【发布时间】:2016-09-04 20:43:11
【问题描述】:
我有一个名为 _updatedComponents 的数组,其中包含 NetworkComponent 类的对象。我必须以更改根元素(=array)的名称和命名空间并将单个 NetworkComponent-item 的名称更改为组件的方式对其进行序列化。我下面有一个导致异常的代码:
System.InvalidOperationException:出现反映类型“ComponentSyncService.NetworkComponent[]”的错误。 ---> System.InvalidOperationException:不能为类型 ComponentSyncService.NetworkComponent[] 指定 XmlRoot 和 XmlType 属性。
代码:
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);
【问题讨论】:
-
我可能会补充一点,我不想更改 System.Xml.Serialization.XmlTypeAttribute 定义,因为生成了类,因此重新生成时更改将丢失
标签: c# .net xml-serialization