XML mapping to objects without attributes in C#

不羁岁月 提交于 2019-12-12 18:01:38

问题


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:


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.



来源:https://stackoverflow.com/questions/14641646/xml-mapping-to-objects-without-attributes-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!