XML mapping to objects without attributes in C#

2019-07-20 09:25发布

Is there a C# library that allows mapping C# objects to XML without Attributes?

I have several data sources, all of them containing XML data with the same logical-structure, but different schema. For example in one XML there might be a field called 'zip-code', in another this data will be in attribute called 'postal-code' etc. I want to deserialize all XML sources in single C# class.

Obviously I can not use XMLAttrubtes, because there are different 'paths'. I want something like EclipseLink MOXy (metadata is specified in XML), but for C#.

1条回答
我想做一个坏孩纸
2楼-- · 2019-07-20 09:50

The XmlSerializer allows you to specify attribute overrides dynamically at runtime. Let's suppose that you have the following static class:

public class Foo
{
    public string Bar { get; set; }
}

and the following XML:

<?xml version="1.0" encoding="utf-8" ?> 
<foo bar="baz" />

you could dynamically add the mapping at runtime without using any static attributes on your model class. Just like this:

using System;
using System.Xml;
using System.Xml.Serialization;

public class Foo
{
    public string Bar { get; set; }
}

class Program
{
    static void Main()
    {
        var overrides = new XmlAttributeOverrides();
        overrides.Add(typeof(Foo), new XmlAttributes { XmlRoot = new XmlRootAttribute("foo") });
        overrides.Add(typeof(Foo), "Bar", new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("bar") });
        var serializer = new XmlSerializer(typeof(Foo), overrides);
        using (var reader = XmlReader.Create("test.xml"))
        {
            var foo = (Foo)serializer.Deserialize(reader);
            Console.WriteLine(foo.Bar);
        }
    }
}

Now all that's left for you is to write some custom code that might read an XML file containing the attribute overrides and building an instance of XmlAttributeOverrides from it at runtime that you will feed to the XmlSerializer constructor.

查看更多
登录 后发表回答