由于工作的需要,自己写了一个exmaple on 反序列 xml data 成 自定义的一个object:
主体:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace NextLabs.RemindwithEmail
{
class Program
{
static void Main(string[] args)
{
emailcollection emails = null;
string path = Directory.GetCurrentDirectory().ToString() + @"\" + "EmailInformation.xml";
XmlSerializer serializer = new XmlSerializer(typeof(emailcollection));
StreamReader reader = new StreamReader(path);
emails = (emailcollection)serializer.Deserialize(reader);
reader.Close();
foreach (email myemail in emails)
{
Console.WriteLine(myemail.smtp);
Console.WriteLine(myemail.to);
Console.WriteLine(myemail.port);
Console.WriteLine(myemail.subject);
}
}
}
}
辅助:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Collections;
namespace NextLabs.RemindwithEmail
{
[Serializable]
public class email
{
[System.Xml.Serialization.XmlElement("smtp")]
public string smtp { get; set; }
[System.Xml.Serialization.XmlElement("port")]
public string port { get; set; }
[System.Xml.Serialization.XmlElement("to")]
public string to { get; set; }
[System.Xml.Serialization.XmlElement("subject")]
public string subject { get; set; }
}
[Serializable]
[System.Xml.Serialization.XmlRoot("emailcollection")]
public class emailcollection : IEnumerable
{
[System.Xml.Serialization.XmlArray("emailcollection")]
[System.Xml.Serialization.XmlArrayItem("email",typeof(email))]
public List<email> emails
{
get
{
return _emails;
}
set
{
_emails = value;
}
}
private List<email> _emails;
public void Add(object o)
{
if (_emails == null)
_emails = new List<email>();
_emails.Add(o as email);
}
public emailEnum GetEnumerator()
{
return new emailEnum(emails);
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) GetEnumerator();
}
}
public class emailEnum : IEnumerator
{
public List<email> _emailcollection;
int postion = -1;
public emailEnum(List<email> list)
{
_emailcollection = list;
}
public void Reset()
{
postion = -1;
}
public bool MoveNext()
{
postion++;
return (postion < _emailcollection.Count);
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public email Current
{
get
{
try
{
return _emailcollection[postion];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
}
在这里我遇到几个问题:
1. 反序列时候XmlArray("emailcollection") 对应的变量不能被定义为 List, 只能定义为 array。 其实是错的。 可以被定义为 list。
[System.Xml.Serialization.XmlArray("emailcollection")]
[System.Xml.Serialization.XmlArrayItem("email",typeof(email))]
public List<email> emails
2. 自定义的collection 要能使用foreach statoment,必须实现Getenumerator() 方法
微软解释
An IEnumeratorobject that can be used to iterate through the collection.