日期:2014-05-18  浏览次数:20755 次

这个结构的XML文件,如何序列化
RT, Value的节点数量不确定。

XML code
  <Measurement Name="SpdupPlinqVs1">
    <value>100</value>
    <value>110</value>
    <value>120</value>
  </Measurement>


------解决方案--------------------
C# code

[XmlRootAttribute("Measurement")]
public class MeasurementResult
{
    [NonSerialized]
    private string measurementName = "";
    [NonSerialized]
    private List<string> valueList = new List<string>();

    public MeasurementResult()
    { 
    }

    [XmlAttribute("Name")]
    public string MeasurementName
    {
        get
        {
            return measurementName;
        }
        set
        {
            measurementName = value;
        }
    }

    [XmlArrayItem("value")]
    public List<string> ValueList
    {
        get
        {
            return valueList;
        }
        set
        {
            valueList.Clear();
            if (value != null)
            {
                valueList.AddRange(value);
            }
        }
    }
}

private void Serialize()
{
    string filePath = "e:\\111111.xml";
    MeasurementResult result = new MeasurementResult();
    result.MeasurementName = "test";
    result.ValueList.AddRange(new string[] { "1", "2", "3" });
    XmlSerializer mySerializer = new XmlSerializer(typeof(MeasurementResult));
    StreamWriter myWriter = new StreamWriter(filePath);
    XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
    xmlns.Add(String.Empty, String.Empty);
    mySerializer.Serialize(myWriter, result, xmlns);
    myWriter.Close();
}

private MeasurementResult Deserialize()
{
    string filePath = "e:\\111111.xml";
    XmlSerializer mySerializer = new XmlSerializer(typeof(MeasurementResult));
    FileStream myFileStream = new FileStream(filePath, FileMode.Open);
    MeasurementResult result = mySerializer.Deserialize(myFileStream) as MeasurementResult;
    myFileStream.Close();
    return result;
}