c# - 序列化为 XML 非嵌套重复序列

标签 c# xml-serialization

我需要序列化为具有多个非嵌套值的数组,即

 <MyArray>
    <Code>code1</Code>
    <Name>name associated with code 1</Name>
    <Code>code2</Code>
    <Name>name associated with code 2</Name>
    <Code>code3</Code>
    <Name>name associated with code 3</Name>
    <Code>code4</Code>
    <Name>name associated with code 4</Name>
  </MyArray>

我已经在我的数组上尝试了各种属性——例如

[XmlArray(ElementName="MyArray")]        
[XmlArrayItem(ElementName="")]        
public List<MyPair> MyPairs { get; set; }

注意:MyPair 对象包含 2 个字符串属性(代码和名称):

但无济于事,我总是为每对获取一个包含元素(这通常会更好,但不是模式所要求的——而且我无法控制)。非常感谢任何帮助。

编辑这是一个巨大的 xml 文档的一部分,是否可以对其中的一部分使用 XElement 的手动序列化,对其余部分使用 XMLSerialization?

最佳答案

除了手动序列化您的项目外,我看不到其他方法。

XElement xElem = new XElement("MyArray", 
                               array.Select(m => new XElement[] { 
                                               new XElement("Code", m.Code), 
                                               new XElement("Name", m.Name) })
                              );
var xml = xElem.ToString();

关于c# - 序列化为 XML 非嵌套重复序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13285309/

相关文章:

c# - RavenDb 索引用于对嵌套结构/集合的属性进行过滤和排序(扇出索引)

xml - 将 Delphi 对象树序列化为 XML 的好方法是什么——使用 RTTI 而不是自定义代码?

c# - XmlSerializer 在反序列化时抛出异常

c# - aspx页面超时过期错误

c# - 使用 C++ 和 .NET 或其他语言的桌面应用程序

c# - 从 C# 添加 Windows 功能

c# - 基于 XSD 的 .Net XML 序列化?

c# - 如何更改 Xml 序列化中的数组元素名称?

c# - 将 pdf 文件存储在数据库中