Skip to content

XmlSerializer throws error when both class and superclass have a property with the XmlAnyElement attribute. #27571

@santiagocabrera96

Description

@santiagocabrera96

When I run this code, it throws exception at line 26. If I take the property of the subclass or the superclass the exception is not thrown.

Code:

using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    public class Program
    {
        static void Main()
        {
            Obj2 obj2 = ParseFromXml<Obj2>(@"C:\Users\user\Downloads\CollectionOfObjects.xml");
            Serialize<Obj2>(obj2, @"C:\Users\user\Downloads\CollectionOfObjects-copy.xml");
        }
        public class Obj1
        {
            [XmlAnyElement] public XmlElement[] elements { get; set; }
        }
        [XmlType("CollectionOfObjects")]
        public class Obj2 : Obj1
        {
            [XmlAnyElement] public XmlElement[] elementos { get; set; }
        }
        private static T ParseFromXml<T>(string ruta)
        {
            var xs = new XmlSerializer(typeof(T));
            using (Stream s = File.OpenRead(ruta))
                return (T)xs.Deserialize(s);
        }
        private static void Serialize<T>(T obj, string path)
        {
            var xs = new XmlSerializer(typeof(T));
            var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };
            if (!Directory.Exists(Path.GetDirectoryName(path)))
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            using (var xmlWriter = XmlWriter.Create(path, settings))
            {
                var ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                xs.Serialize(xmlWriter, obj, ns);
            }
        }
    }
}

CollectionOfObjects.xml

<CollectionOfObjects>
  <Name>Something</Name>
  <Description>Some description.</Description>
  <Object>
    <Name>Name Of Object</Name>
    <Description>Description of object.</Description>
    <AltName>Alternate name</AltName>
    <ContainerName>Container</ContainerName>
    <Required>true</Required>
    <Length>1</Length>
    <Info>
      <Name>Name</Name>
      <File>Filename</File>
      <Size>20</Size>
      <SizeUnit>MB</SizeUnit>
    </Info>
  </Object>
</CollectionOfObjects>

Exception:

System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=There was an error reflecting type 'ConsoleApplication1.Program.Obj2'.
  Source=System.Xml
  StackTrace:
       at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
       at System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel model, XmlRootAttribute root, String defaultNamespace, RecursionLimiter limiter)
       at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
       at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
       at System.Xml.Serialization.XmlSerializer..ctor(Type type)
       at ConsoleApplication1.Program.ParseFromXml[T](String ruta) in C:\Users\user\Downloads\ConsoleApplication1\ConsoleApplication1\Program.cs:line 26
       at ConsoleApplication1.Program.Main() in C:\Users\user\Downloads\ConsoleApplication1\ConsoleApplication1\Program.cs:line 12
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
       HResult=-2146233079
       Message=There was an error reflecting property 'elementos'.
       Source=System.Xml
       StackTrace:
            at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
            at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter)
            at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
       InnerException: 
            HResult=-2146233079
            Message=The XML element '' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.
            Source=System.Xml
            StackTrace:
                 at System.Xml.Serialization.XmlReflectionImporter.AddUniqueAccessor(INameScope scope, Accessor accessor)
                 at System.Xml.Serialization.XmlReflectionImporter.AddUniqueAccessor(MemberMapping member, INameScope elements, INameScope attributes, Boolean isSequence)
                 at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
            InnerException: 

image

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions