XmlSerializerExtensions.cs
2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
namespace SoapCore
{
/// <summary>Extensions to <see cref="XmlSerializer"/>.</summary>
public static class XmlSerializerExtensions
{
/// <summary>
/// Deserializes the XML document contained by the specified <see cref="XmlReader"/>.
/// </summary>
/// <typeparam name="T"> The type of the object that this <see cref="XmlSerializer"/> can serialize.</typeparam>
/// <param name="serializer">The <see cref="XmlSerializer"/>.</param>
/// <param name="localname">The string to match against the LocalName property of the element found.</param>
/// <param name="ns">The string to match against the NamespaceURI property of the element found.</param>
/// <param name="xmlReader">The System.xml.XmlReader that contains the XML document to deserialize.</param>
/// <returns>The objects being deserialized.</returns>
/// <exception cref="InvalidOperationException">
/// An error occurred during deserialization. The original exception is available
/// using the <see cref="Exception.InnerException"/> property.
/// </exception>
public static T[] DeserializeArray<T>(this XmlSerializer serializer, string localname, string ns, XmlReader xmlReader)
{
var argument = new List<T>();
while (xmlReader.IsStartElement(localname, ns))
{
argument.Add((T)serializer.Deserialize(xmlReader));
}
return argument.ToArray();
}
/// <summary>
/// Serializes the specified objects and writes the XML document to a file using the specified <see cref="XmlWriter"/>.
/// </summary>
/// <param name="serializer">The <see cref="XmlSerializer"/>.</param>
/// <param name="xmlWriter">The <see cref="XmlWriter"/> used to write the XML document.</param>
/// <param name="os">The objects to serialize.</param>
/// <exception cref="InvalidOperationException">
/// An error occurred during serialization. The original exception is available using
/// the <see cref="Exception.InnerException"/> property.
/// </exception>
public static void SerializeArray(this XmlSerializer serializer, XmlWriter xmlWriter, object[] os)
{
foreach (var o in os)
{
serializer.Serialize(xmlWriter, o);
}
}
}
}