Skip to content

Commit

Permalink
Support XmlEnumAttribute #3
Browse files Browse the repository at this point in the history
  • Loading branch information
JohanLarsson committed Sep 12, 2018
1 parent c50ea2b commit 536e26e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
19 changes: 18 additions & 1 deletion Gu.Xml.Tests/XmlTests.SerializeWithXmlAttributes.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#pragma warning disable SA1201 // Elements should appear in the correct order
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable MemberCanBePrivate.Global
#pragma warning disable SA1201 // Elements should appear in the correct order
namespace Gu.Xml.Tests
{
using System;
Expand All @@ -25,6 +27,8 @@ public class SerializeWithXmlAttributes
new TestCaseData(new FieldWithXmlElementAttributeExplicitName { Value = 1 }),
new TestCaseData(new FieldWithXmlAttributeAttribute { Value = 1 }),
new TestCaseData(new FieldWithXmlAttributeAttributeExplicitName { Value = 1 }),
new TestCaseData(new With<WithXmlEnumAttribute> { Value = WithXmlEnumAttribute.One }),
new TestCaseData(new With<WithXmlEnumAttribute> { Value = WithXmlEnumAttribute.Two }),
};

[TestCaseSource(nameof(Values))]
Expand Down Expand Up @@ -138,6 +142,19 @@ public class FieldWithXmlIgnoreAttribute
[XmlIgnore]
public int Value { get; set; }
}

public class With<T>
{
public T Value { get; set; }
}

public enum WithXmlEnumAttribute
{
[XmlEnum(Name = "Single")]
One,
[XmlEnum(Name = "Double")]
Two,
}
}
}
}
17 changes: 16 additions & 1 deletion Gu.Xml/Writers/EnumWriter{T}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Xml.Serialization;

public sealed class EnumWriter<T>
where T : struct, Enum
Expand All @@ -27,7 +28,21 @@ private EnumWriter(string format)

public void Write(TextWriter writer, T value)
{
writer.Write(this.cache.GetOrAdd(value, Enum.Format(typeof(T), value, this.format).Replace(",", string.Empty)));
writer.Write(this.cache.GetOrAdd(value, x => this.ToString(x)));
}

private string ToString(T value)
{
if (typeof(T).GetMember(value.ToString())
.TryFirst(out var member) &&
member.TryGetCustomAttribute<XmlEnumAttribute>(out var attribute) &&
attribute.Name is string text &&
!string.IsNullOrEmpty(text))
{
return text;
}

return Enum.Format(typeof(T), value, this.format).Replace(",", string.Empty);
}
}
}

0 comments on commit 536e26e

Please sign in to comment.