/
XmlUnknown.cs
128 lines (112 loc) · 5.56 KB
/
XmlUnknown.cs
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// Copyright Bastian Eicher et al.
// Licensed under the GNU Lesser Public License
using System.Reflection;
using System.Xml;
namespace ZeroInstall.Model;
/// <summary>
/// Abstract base class for XML serializable classes that are intended to retain any unknown XML elements or attributes loaded from an XML file.
/// </summary>
/// <remarks>Inheriting from this class will prevent the <see cref="XmlSerializer.UnknownElement"/> event from being triggered.</remarks>
public abstract class XmlUnknown : IEquatable<XmlUnknown>
{
/// <summary>
/// Contains any unknown additional XML attributes.
/// </summary>
[XmlAnyAttribute]
public XmlAttribute[]? UnknownAttributes;
/// <summary>
/// Contains any unknown additional XML elements.
/// </summary>
[XmlAnyElement]
public XmlElement[]? UnknownElements;
/// <summary>
/// Ensures that a value deserialized from an XML attribute is set (not <c>null</c>).
/// </summary>
/// <param name="value">The mapped value to check.</param>
/// <param name="attributeName">The name of the XML attribute.</param>
/// <exception cref="InvalidDataException"><paramref name="value"/> is <c>null</c>.</exception>
protected void EnsureAttribute(object? value, string attributeName)
{
if (value == null)
throw new InvalidDataException(string.Format(Resources.MissingXmlAttributeOnTag, attributeName, ToShortXml()));
}
/// <summary>
/// Ensures that a value deserialized from an XML attribute is set (not <c>null</c>) and only contains alphanumeric characters, spaces ( ), dots (.), underscores (_), hyphens (-) and plus signs (+).
/// </summary>
/// <param name="value">The mapped value to check.</param>
/// <param name="attributeName">The name of the XML attribute.</param>
/// <exception cref="InvalidDataException"><paramref name="value"/> is invalid.</exception>
protected void EnsureAttributeSafeID(string? value, string attributeName)
{
if (string.IsNullOrEmpty(value) || !value.All(x => char.IsLetterOrDigit(x) || x is ' ' or '.' or '_' or '-' or '+'))
throw new InvalidDataException($"{string.Format(Resources.InvalidXmlAttributeOnTag, attributeName, ToShortXml())} {Resources.ShouldBeSafeID} {Resources.FoundInstead} {value}");
}
/// <summary>
/// Returns a shortened XML representation (with attributes but without child elements).
/// </summary>
/// <remarks>
/// Intended for use in error messages. Not suitable for parsing.
/// Use <see cref="XmlStorage.ToXmlString"/> instead if you need a full XML representation.
/// </remarks>
public string ToShortXml()
=> this.ToXmlString()
.Split('\n')[1]
.Replace($" xmlns=\"{GetType().GetCustomAttribute<XmlRootAttribute>()?.Namespace}\"", "")
.Replace(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "")
.Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
#region Comparers
private class XmlAttributeComparer : IEqualityComparer<XmlAttribute>
{
public static readonly XmlAttributeComparer Instance = new();
public bool Equals(XmlAttribute? x, XmlAttribute? y)
{
if (x == null || y == null) return false;
return x.NamespaceURI == y.NamespaceURI && x.Name == y.Name && x.Value == y.Value;
}
public int GetHashCode(XmlAttribute obj)
=> HashCode.Combine(obj.Name, obj.Value);
}
private class XmlElementComparer : IEqualityComparer<XmlElement>
{
public static readonly XmlElementComparer Instance = new();
public bool Equals(XmlElement? x, XmlElement? y)
{
if (x == null || y == null) return false;
if (x.NamespaceURI != y.NamespaceURI || x.Name != y.Name || x.InnerText != y.InnerText) return false;
// ReSharper disable once InvokeAsExtensionMethod
bool attributesEqual = EnumerableExtensions.UnsequencedEquals(
x.Attributes.OfType<XmlAttribute>().ToArray(),
y.Attributes.OfType<XmlAttribute>().ToArray(),
comparer: XmlAttributeComparer.Instance);
bool elementsEqual = EnumerableExtensions.SequencedEquals(
x.ChildNodes.OfType<XmlElement>().ToArray(),
y.ChildNodes.OfType<XmlElement>().ToArray(),
comparer: Instance);
return attributesEqual && elementsEqual;
}
public int GetHashCode(XmlElement obj)
=> HashCode.Combine(obj.Name, obj.Value);
}
#endregion
#region Equatable
public bool Equals(XmlUnknown? other)
{
if (other == null) return false;
// ReSharper disable once InvokeAsExtensionMethod
bool attributesEqual = EnumerableExtensions.UnsequencedEquals(
UnknownAttributes ?? [],
other.UnknownAttributes ?? [],
comparer: XmlAttributeComparer.Instance);
bool elementsEqual = EnumerableExtensions.SequencedEquals(
UnknownElements ?? [],
other.UnknownElements ?? [],
comparer: XmlElementComparer.Instance);
return attributesEqual && elementsEqual;
}
/// <inheritdoc/>
public override int GetHashCode()
=> HashCode.Combine(
(UnknownAttributes ?? []).GetUnsequencedHashCode(XmlAttributeComparer.Instance),
(UnknownElements ?? []).GetSequencedHashCode(XmlElementComparer.Instance));
#endregion
}