反序列化XML文件并将值复制到csv中

时间:2014-04-18 09:55:04

标签: c# xml deserialization

我想反序列化一个xml文件并将这些值复制到csv file.i中试试这样。

 [Serializable, XmlRoot("Configuration"), XmlType("Configuration")]
        public class LabelRequest
        {
           public string weightoz { get; set; }
           public string MailClass { get; set; }

            public static void DeSerialization()
            {
               LabelRequest label = new LabelRequest();
               TextReader txtReader = new StreamReader(@"C:\xmlfile.xml");
               XmlSerializer xmlSerializer = new XmlSerializer(typeof(LabelRequest));
               label = (LabelRequest) xmlSerializer.Deserialize(txtReader);
               txtReader.Close();
            }

        }

和xml文件如下

<Labelrequest>
     <weightoz>2</weightoz>
     <mailclass>abc</mailclass>
</labelrequest>

1 个答案:

答案 0 :(得分:3)

将值写入CSV文件应该不会太困难。您的示例不包含任何写入文件的代码。它只反序列化一个XML文件。我可能会建议这样的事情。

    public static class LabelRequestSerializer
    {
        public static Label DeserializeXmlFile(string fileName)
        {
           using (TextReader txtReader = new StreamReader(fileName))
           {
               XmlSerializer xmlSerializer = new XmlSerializer(typeof(LabelRequest));
               LabelRequest label = (LabelRequest) xmlSerializer.Deserialize(txtReader);
           }
        }

        public static void SerializeToCsv(LabelRequest labelRequest, string fileName)
        {
             if (labelRequest == null)
                throw new ArgumentNullException("labelRequest");

             StringBuilder sb = new StringBuilder();
             sb.Append(labelRequest.weightoz);
             sb.Append(",");
             sb.Append(labelRequest.mailclass);
             sb.AppendLine();

             using (StreamWriter stream = new StreamWriter(fileName))
             {
                 stream.Write(sb.ToString());
             }
        }
    }

然后,您可以将要序列化的LabelRequest实例传递给这些静态方法。这样,LabelRequest不知道如何从文件中序列化自己,这是一个很好的分离问题。喜欢这个

void SomeMethod()
{
    LabelRequest labelRequest = new LabelRequest();
    LabelRequestSerializer.SerializeToCsv(labelRequest, @"C:\Path\Goes\Here\label.csv");
}

编辑...

如果您真的不想手动写出每个属性,可以使用反射。但是,使用它会受到性能影响。虽然与文件IO相比应该不是问题。

public static void SerializeToCsv(LabelRequest labelRequest, string fileName)
        {
             if (labelRequest == null)
                throw new ArgumentNullException("labelRequest");

             StringBuilder sb = new StringBuilder();

            foreach (PropertyInfo info in labelRequest.GetType() .GetProperties()) 
            {
                   object value =   info.GetValue(labelRequest, null);
                    sb.Append(value);
                    sb.Append(", ");
             } 

             sb.AppendLine();
             using (StreamWriter stream = new StreamWriter(fileName))
             {
                 stream.Write(sb.ToString());
             }
        }