请帮忙:
我需要做的:我从浏览器栏中传入一个 XML 文件,然后尝试将 XML 文件中的数据映射到类中的对象类型。
有许多不同的对象类型,所以如果我为每个序列化和反序列化编写类,那将是太多的工作。
我搜索了一些用于序列化和反序列化的代码并尝试了它们,它们可以编译,但是很多数据都丢失了。
我的序列化和反序列化代码在这里:
string InputFilePath = FileUpload1.PostedFile.FileName;
MyServiceTypeClass _MyServiceTestObj = new MyServiceTypeClass ();
XmlSerializer SerializerObj = new XmlSerializer(typeof(MyServiceTypeClass ));
StreamWriter WriteFileStream = new StreamWriter(@InputFilePath);
SerializerObj.Serialize(WriteFileStream, _MyServiceTestObj );
WriteFileStream.Close();
FileStream XmlStream = new FileStream(@InputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
MyServiceTypeClass _ServiceTypeLoaded = (MyServiceTypeClass )SerializerObj.Deserialize(XmlStream);
XmlStream.Close();
MyServiceTypeClass 定义:
public class MyServiceType: UpperLevel1
{
[DataMember]
public TypeDefinition Definition;
[DataMember]
public Type Type;
[DataMember]
public string a;
[DataMember]
public double? b;
}
public class UpperLevel1: UpperLevel2
{
[DataMember(IsRequired = true)]
public double a;
[DataMember]
public double? b;
[DataMember]
public double? c;
[DataMember]
public double? d;
}
etc until 5 levels
原始 Xml 是:
<?xml version="1.0" encoding="utf-8" ?>
<ns0:BondTransaction xmlns:ns0="ABC" xmlns:ns1="http://schemas.microsoft.com/2003/10/Serialization/">
<ns0:a>0</ns0:a>
<ns0:m1>Something</ns0:m1>
<ns0:b>Remain1</ns0:b>
<ns0:m2> Something </ns0:m2>
<ns0:m2a>
<ns0:m2b>
<ns0:m2c>
<ns0:m2d>
<ns0:m2d1>Position</ns0:m2d1>
<ns0:m2d2>BAR</ns0:m2d2>
</ns0:m2d>
</ns0:m2c>
<ns0:m2b2>Remain2</ns0:m2b2>
</ns0:m2b>
</ns0:m2a>
<ns0:m3>12345</ns0:m3>
<ns0:m4>SomeCOMPANY</ns0:m4>
<ns0:m5>TRAD</ns0:m5>
<ns0:m6>12345</ns0:m6>
<ns0:m7>Time</ns0:m7>
<ns0:SomeDesign>
<ns0:Property>
<ns0:Type>type1</ns0:Type>
<ns0:Value>somevalue</ns0:Value>
</ns0:Property>
</ns0:SomeDesign>
<ns0:Price>1</ns0:Price>
<ns0:QuotationCurrency>USD</ns0:QuotationCurrency>
<ns0:SomeOtherDesign>
<ns0:Property>
<ns0:Type>typ2</ns0:Type>
<ns0:Value>gfgg</ns0:Value>
</ns0:Property>
<ns0:Property>
<ns0:Type>fer</ns0:Type>
<ns0:Value>getrt</ns0:Value>
</ns0:Property>
</ns0:SomeOtherDesign>
<ns0:Exchange>hmmm</ns0:Exchange>
</ns0:BondTransaction>
xml 看起来像这样的后记:
<?xml version="1.0" encoding="utf-8" ?>
- <big xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<a>0</a>
<b>INSERT</b>
<g xsi:nil="true" />
<r xsi:nil="true" />
<rw>AGAINST</rw>
<rwer xsi:nil="true" />
<gfg>TRAD</gfg>
<a xsi:nil="true" />
<b xsi:nil="true" />
<c xsi:nil="true" />
<d xsi:nil="true" />
<e xsi:nil="true" />
<f xsi:nil="true" />
<h xsi:nil="true" />
<sd xsi:nil="true" />
<s xsi:nil="true" />
<gf>0</gf>
<y xsi:nil="true" />
<ted xsi:nil="true" />
<ty xsi:nil="true" />
<yt xsi:nil="true" />
<uy>DEFAULT</uy>
<tert xsi:nil="true" />
<tr xsi:nil="true" />
</big>
任何人都可以告诉我出了什么问题或告诉我应该怎么做才能完成我的目标吗?太谢谢了。