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

时间:2016-02-01 04:13:25

标签: c# xml xml-serialization

我需要将一些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维护该结构吗?

2 个答案:

答案 0 :(得分:0)

因此,我一直在寻找解决方案并提出这个并不是我想要的。此类结构保留集合中兄弟元素的顺序,但不创建表示兄弟节点的离散组的对象。

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中的顺序的集合。

答案 1 :(得分:-1)

您可以尝试以下步骤:

  1. 使用xsd.exe(VS的功能)
  2. 将xml转换为xslt
  3. 使用xsd.exe
  4. 将xslt再次转换为类
  5. 尝试将xml序列化并反序列化为此类对象。
  6. 现在您可以使用此类对象来执行任何操作。
  7. 希望这会有所帮助..

相关问题