使用平面重复结构序列化 XML

Serializing XML with flat repeating structure

我需要将一些 XML 序列化为一个对象。我无法控制 XML 的结构,所以我遇到了这种情况。结构类似于这个例子:

<A>
  <B>Elements that are the stuff of B</B>
  <C>Stuff about the stuff in B</C>
  <B>Different stuff</B>
  <C>Stuff about the different stuff</C>
  <C>Some more stuff about the different stuff</C>
  <B>Weird stuff</B>
  <C>Stuff about the Weird Stuff</C>
  <C>Still more stuff about the Weird Stuff</C>
  <D>New thing that goes with the Weird Stuff</D>
  <B>Things</B>
  <C>Stuff about Things</C>
 </A>

我想将此序列化为一个对象,该对象维护有关同级结构的信息。

public class A
{
 public List<BCD> BCD {get; set;}
}

public class BCD
{
 public B Bfield {get; set;}
 public List<C> Cfield {get; set;}
 public D Dfield {get; set;}
}

public class B
{
 // class details
}

public class C
{
 // class details
}

public class D
{
 // class details
}

当我尝试这个时,它不起作用。我可以做些什么来使用 XMLSerializer 维护该结构吗?

您可以尝试以下步骤:

  1. 使用 xsd.exe(VS 的功能)
  2. 将您的 xml 转换为 xslt
  3. 使用 xsd.exe
  4. 再次将 xslt 转换为 class
  5. 尝试将您的 xml 序列化和反序列化到此 class 对象。
  6. 现在您可以玩这个 class 对象来执行任何操作。

希望这会有所帮助..

所以我一直在四处寻找解决方案并想出了这个,但这并不是我想要的。此 class 结构保留了集合中兄弟元素的顺序,但不创建对象来表示离散的兄弟元素组。

public class A
{
 [XmlElementAttribute("B", typeof(B))]
 [XmlElementAttribute("C", typeof(C))]
 [XmlElementAttribute("D", typeof(D))]
 public List<object> BCD {get; set;}
}

public class B
{
 // class details
}

public class C
{
 // class details
}

public class D
{
 // class details
}

最终结果是 BCD 是 B、​​C、D 对象的集合,按照它们在 XML 中出现的顺序排列。