我想序列CMainClass:如何序列CustomClass的列表與對象屬性
[XmlType("Param")]
public class CParam
{
[XmlElement]
public string Name;
[XmlElement]
public object Value;
public CParam() { }
public CParam(string name, object value)
{
Name = name;
Value = value;
}
}
public class CMainClass
{
public List<CParam> Parameters = new List<CParam>();
public CMainClass() { }
public string GetXML()
{
XmlDocument doc = new XmlDocument();
Type[] extraTypes = new Type[1];
extraTypes[0] = typeof(CParam);
XmlSerializer serializer = new XmlSerializer(typeof(CMainClass), extraTypes);
MemoryStream stream = new MemoryStream();
try
{
serializer.Serialize(stream, this);
stream.Position = 0;
doc.Load(stream);
return doc.InnerXml;
}
catch { throw; }
finally
{
stream.Close();
stream.Dispose();
}
}
}
type屬性值可以是不同的,這是爲什麼對象類型使用。
這裏是測試代碼
CMainClass mc = new CMainClass();
mc.Parameters.Add(new CParam("number", 123));
mc.Parameters.Add(new CParam("text", "lorem ipsum"));
mc.Parameters.Add(new CParam("price", 23.50));
string s = mc.GetXML();
Console.WriteLine(s);
Console.ReadLine();
我要的是以下形式
<?xml version="1.0"?>
<CMainClass>
<Parameters>
<Param Name="number" Value="123" />
<Param Name="text" Value="lorem ipsum" />
<Param Name="price" Value="23.5" />
</Parameters>
</CMainClass>
代替
<?xml version="1.0"?>
<CMainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Parameters>
<Param>
<Name>number</Name>
<Value xsi:type="xsd:int">123</Value>
</Param>
<Param>
<Name>text</Name>
<Value xsi:type="xsd:string">lorem ipsum</Value>
</Param>
<Param>
<Name>price</Name>
<Value xsi:type="xsd:double">23.5</Value>
</Param>
</Parameters>
</CMainClass>
是否有可能得到的輸出?將值的屬性從[XmlElement]更改爲[XmlAttribute]會導致錯誤。
你知道使用該構造函數的內存泄漏嗎? http://blog.forse.no/xmlserializer-causes-memory-leaks/ – Aphelion