Skip to content

Commit

Permalink
Handle SoapEnumAttribute #3.
Browse files Browse the repository at this point in the history
  • Loading branch information
JohanLarsson committed Sep 12, 2018
1 parent 536e26e commit d504aa3
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 8 deletions.
17 changes: 16 additions & 1 deletion Gu.Xml.Tests/XmlTests.SerializeWithSoapAttributes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ public class SerializeWithSoapAttributes
new TestCaseData(new FieldWithSoapElementAttributeExplicitName { Value = 1 }),
new TestCaseData(new FieldWithSoapAttributeAttribute { Value = 1 }),
new TestCaseData(new FieldWithSoapAttributeAttributeExplicitName { Value = 1 }),
new TestCaseData(new With<WithSoapEnumAttribute> { Value = WithSoapEnumAttribute.One }),
new TestCaseData(new With<WithSoapEnumAttribute> { Value = WithSoapEnumAttribute.Two }),
};

[TestCaseSource(nameof(Values))]
public void Serialize(object value)
{
var expected = Reference.XmlSerializerSoap(value);
var expected = Reference.XmlSerializerSoap(value).Replace(" xsi:type=\"WithSoapEnumAttribute\"", string.Empty);
var actual = Xml.Serialize(value);
if (actual == expected)
{
Expand Down Expand Up @@ -141,6 +143,19 @@ public class FieldWithSoapIgnoreAttribute
[SoapIgnore]
public int Value { get; set; }
}

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

public enum WithSoapEnumAttribute
{
[SoapEnum(Name = "Single")]
One,
[SoapEnum(Name = "Double")]
Two,
}
}
}
}
26 changes: 19 additions & 7 deletions Gu.Xml/Writers/EnumWriter{T}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;

public sealed class EnumWriter<T>
where T : struct, Enum
Expand Down Expand Up @@ -33,16 +33,28 @@ public void Write(TextWriter writer, T value)

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))
if (typeof(T).GetMember(value.ToString()).TryFirst(out var member))
{
return text;
if (TryGetNameFromAttribute<System.Xml.Serialization.XmlEnumAttribute>(member, x => x.Name, out var name) ||
TryGetNameFromAttribute<System.Xml.Serialization.SoapEnumAttribute>(member, x => x.Name, out name))
{
return name;
}
}

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

private static bool TryGetNameFromAttribute<T>(MemberInfo type, Func<T, string> getName, out string name)
where T : Attribute
{
name = null;
if (type.TryGetCustomAttribute(out T attribute))
{
name = getName(attribute);
}

return !string.IsNullOrEmpty(name);
}
}
}

0 comments on commit d504aa3

Please sign in to comment.