使用平面重复结构序列化 XML
本文关键字:结构 序列化 XML 平面 | 更新日期: 2023-09-27 18:32:37
我需要将一些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的结构吗?
所以我一直在四处寻找解决方案,并提出了这个,这不是我想要的。此类结构保留集合中同级元素的顺序,但不创建对象来表示同级元素的离散组。
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 中出现的顺序的集合。
您可以尝试以下步骤:
- 使用 XSD.exe 将 XML 转换为 XSLT(VS 的功能)
- 使用 XSD 再次将 XSLT 转换为类.exe
- 尝试将 XML 序列化和反序列化为此类对象。
- 现在,您可以使用此类对象来执行任何操作。
希望这会有所帮助..