From 73e1752fcef12f3bf54a3032ee99e28599d387f6 Mon Sep 17 00:00:00 2001 From: Johan Larsson Date: Sun, 9 Sep 2018 18:31:14 +0200 Subject: [PATCH] Handle XmlRootAttribute. #3 --- Gu.Xml.Tests/XmlTests.SerializeComplextTypes.cs | 8 ++++++++ Gu.Xml/Internals/RootName.cs | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/Gu.Xml.Tests/XmlTests.SerializeComplextTypes.cs b/Gu.Xml.Tests/XmlTests.SerializeComplextTypes.cs index 4e609ad..b77ab0e 100644 --- a/Gu.Xml.Tests/XmlTests.SerializeComplextTypes.cs +++ b/Gu.Xml.Tests/XmlTests.SerializeComplextTypes.cs @@ -4,6 +4,7 @@ namespace Gu.Xml.Tests using System; using System.Collections.Generic; using System.Diagnostics; + using System.Xml.Serialization; using NUnit.Framework; public partial class XmlTests @@ -13,6 +14,7 @@ public class SerializeComplexTypes private static readonly TestCaseData[] Values = { new TestCaseData(new WithPublicMutableProperty { Value = 1 }), + new TestCaseData(new WithXmlRoot { Value = 1 }), new TestCaseData(new WithPublicMutableFieldXmlElementExplicitName { Value = 1 }), new TestCaseData(new WithPublicMutableField { Value = 1 }), new TestCaseData(new WithPublicMutableFieldXmlElementExplicitName { Value = 1 }), @@ -101,6 +103,12 @@ public class WithPublicMutableProperty public int Value { get; set; } = 1; } + [XmlRoot("Name")] + public class WithXmlRoot + { + public int Value { get; set; } = 1; + } + public class WithPublicMutablePropertyXmlElementExplicitName { [System.Xml.Serialization.XmlElement("Name")] diff --git a/Gu.Xml/Internals/RootName.cs b/Gu.Xml/Internals/RootName.cs index 6c6cbf7..b0c264d 100644 --- a/Gu.Xml/Internals/RootName.cs +++ b/Gu.Xml/Internals/RootName.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Concurrent; using System.Text; + using System.Xml.Serialization; internal static class RootName { @@ -15,6 +16,13 @@ public static string Get(Type type) private static string Create(Type type) { + if (Attribute.GetCustomAttribute(type, typeof(XmlRootAttribute)) is XmlRootAttribute xmlRoot && + xmlRoot.ElementName is string elementName && + !string.IsNullOrEmpty(elementName)) + { + return elementName; + } + if (!type.IsGenericType && !type.HasElementType) {