試圖學習和使用更多關於XML的類序列化。 我可以做基本的序列化。如何在c#中實現對XML的分層序列化?
在下面的情況下,我有一個嵌套的類結構,並希望它在其實現的層次結構中輸出到XML標準的文件。如果存在任何警告,則反序列化也是如此。 我有一個很好的搜索,但無法理解如何做到這一點。
我知道下面的一些位並不是100%安全的,但我更擔心序列化功能。序列化程序類將Serialize()擴展到我的任何類。
非常感謝您的幫助。
public class SysConfigs
{
public SysConfigs() { }
public struct DeadVolumes
{
public struct Valve
{
public uint V1; //valve 1 dead volume in uL
public uint V2; //valve 2 deal volume
public uint V3;
public uint V4;
public uint V5p0;
public uint V5p1;
public uint V5p2;
public uint V5p3;
public uint V5p4;
public uint V5p5;
public uint v5p6;
public uint V5p7;
public uint V5p8;
public uint V5p9;
public uint V5p10;
public uint V5p11;
public uint V5p12;
public uint V5p13;
public uint V5p14;
public uint V6;
}
public struct Mixer
{
public uint M1p1;
public uint M1p2;
public uint M1p3;
public uint M2p1;
public uint M2p2;
public uint M2p3;
}
}
}
public static class Serializer
{
public static void Serialize(this Object obj, string filePath)
{
// Creates an instance of the XmlSerializer class;
// specifies the type of object to be deserialized.
XmlSerializer _xml_serializer = new XmlSerializer(obj.GetType());
XmlWriter _xml_textwriter = XmlWriter.Create(filePath);
try
{
_xml_serializer.Serialize(_xml_textwriter, obj);
}
catch (Exception ex)
{
throw ex;
}
_xml_textwriter.Close();
// If the XML document has been altered with unknown
// nodes or attributes, handles them with the
// UnknownNode and UnknownAttribute events.
_xml_serializer.UnknownNode += new XmlNodeEventHandler(serializer_UnknownNode);
_xml_serializer.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);
}
// this is where I am testing the my serialization implementation from
private void button1_Click(object sender, EventArgs e)
{
SysConfigs stuff = new SysConfigs();
stuff.Serialize("myfile.xml");
}
上面的例子產生了一個沒有內容的XML - 這是可以理解的。
<?xml version="1.0" encoding="utf-8"?><SysConfigs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
我想明白了什麼是必需的,因爲上面的例子中,實現了以下XML程序輸出:
<SysConfigs>
<DeadVolumes>
<Valve>
<V1>123</V1>
<V2>123</V2>
<V3>123</V3>
..etc..
</Valve>
<Mixer>
<M1p1>1</M1p1>
<M1p2>1</M1p2>
<M1p3>1</M1p3>
..etc..
</Mixer>
</DeadVolumes>
</SysConfigs>
請閱讀[問]並創建[mcve]。目前還不清楚你究竟在問什麼。 – CodeCaster
@CodeCaster希望更好一點。 – FlashFast
如果問題是「文件爲空」,那是因爲'SysConfig'結構沒有成員。 – CodeCaster