XmlSerializer.Deserialize
接受一个XmlReader
参数。您可以将XmlReader
just 放在<Account>
标签上,然后调用XmlSerializer
那里。
public IEnumerable<Account> ReadAccounts(TextReader source)
{
var ser = new XmlSerializer(typeof(Account));
using (var reader = XmlReader.Create(source))
{
if (!reader.IsStartElement("BillingFile"))
{
yield break;
}
reader.Read();
while (reader.MoveToContent() == XmlNodeType.Element)
{
yield return (Account) ser.Deserialize(reader);
}
}
}
同样对于序列化
public void WriteAccounts(IEnumerable<Account> data, TextWriter target)
{
// Use XmlSerializerNamespaces to supress xmlns:xsi and xmlns:xsd
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("", "");
var ser = new XmlSerializer(typeof(Account));
using (var writer = XmlWriter.Create(target))
{
writer.WriteStartElement("BillingFile");
foreach (var acct in data)
{
ser.Serialize(writer, acct, namespaces);
writer.Flush();
}
writer.WriteEndElement();
}
}
您还可以创建一个BillingFile
实现 的类,IXmlSerializable
并将此功能放在那里。
或者,如果您更喜欢基于推送的模型:
public class AccountWriter : IDisposable
{
private XmlWriter _writer;
private XmlSerializer _ser;
private XmlSerializerNamespaces _namespaces;
private bool _wroteHeader = false;
private bool _disposed = false;
public bool IsDisposed { get { return _disposed; } }
public AccountWriter(TextWriter target)
{
_namespaces = new XmlSerializerNamespaces();
_namespaces.Add("", "");
_ser = new XmlSerializer(typeof(Account));
_writer = XmlWriter.Create(target);
}
public void Write(Account acct)
{
if (_disposed) throw new ObjectDisposedException("AccountWriter");
if (!_wroteHeader)
{
_writer.WriteStartElement("BillingFile");
_wroteHeader = true;
}
_ser.Serialize(_writer, acct, _namespaces);
}
public void Flush()
{
if (_disposed) throw new ObjectDisposedException("AccountWriter");
_writer.Flush();
}
public void Dispose()
{
if (!_disposed)
{
if (_wroteHeader)
{
_writer.WriteEndElement();
_wroteHeader = true;
}
_writer.Dispose();
_disposed = true;
}
}
}
using (var writer = new AccountWriter(Console.Out))
{
foreach (var acct in accounts)
{
writer.Write(acct);
}
}