我正在尝试将ObservableCollection代码序列化为XML文件。当我这样做时,结果XML是这样的:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCode xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Code>
<AccpacCode>ORWC</AccpacCode>
<LAC>94199999999999999</LAC>
<SCSCode>WC</SCSCode>
</Code>
<Code>
<AccpacCode>AK9999</AccpacCode>
<LAC>90299999999999999</LAC>
<SCSCode>UI</SCSCode>
<ParentEmployerAccpacCode>AKSUTA</ParentEmployerAccpacCode>
</Code>
<Code>
<AccpacCode>AL0014</AccpacCode>
<LAC>90107307000999999</LAC>
<SCSCode>IT</SCSCode>
</Code>
<Code>
<AccpacCode>IN0006</AccpacCode>
<LAC>91817599999999999</LAC>
<SCSCode>IT</SCSCode>
</Code>
除非我需要标记Codes
代替ArrayOfCode
,否则这一切都很好。如何指定标签名称?
以下是代码模型:
namespace SerializeObservableCollection.Model
{
[Serializable()]
public class Codes
{
public Codes() { }
[XmlElement("Code")]
public ObservableCollection<Code> CodeCollection { get; set; }
}
[Serializable()]
public class Code
{
[XmlElement("AccpacCode")]
public string AccpacCode { get; set; }
[XmlElement("LAC")]
public string LAC { get; set; }
[XmlElement("SCSCode")]
public string SCSCode { get; set; }
[XmlElement("ParentEmployerAccpacCode")]
public string ParentEmployerAccpacCode { get; set; }
}
}
以下是执行序列化的代码:
private void SaveToXML()
{
try
{
XmlSerializer _serializer = new XmlSerializer(typeof(ObservableCollection<Code>));
using (StreamWriter _writer = new StreamWriter(@"LocalCodes.xml"))
{
_serializer.Serialize(_writer, CodeCollection);
}
}
catch (Exception ex)
{
}
}
答案 0 :(得分:0)
这样,您尝试序列化ObservableCollection类型的对象,很快就无法控制xml标记中显示的名称。您需要另一个名为Codes的类,其属性包含此集合,而XmlElement属性包含参数Code。
var codes = new Codes { CodeCollection = codeCollection };
XmlSerializer _serializer = new XmlSerializer(typeof(Codes));
using (StreamWriter _writer = new StreamWriter(@"LocalCodes.xml"))
{
_serializer.Serialize(_writer, codes);
}