XML映射对象,而在C#中的属性 [英] XML mapping to objects without attributes in C#

查看:160
本文介绍了XML映射对象,而在C#中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个C#库,允许映射C#对象到XML没有属性?

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

我有几个数据源,与同LOGICAL-他们都包含XML数据结构,但不同的架构。例如,在一个XML有可能是一个被称为邮政编码字段,在另一个这一数据将在被称为邮政代码'等。我想反序列化一个C#类的所有XML源属性。

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.

很明显,我不能使用XMLAttrubtes,因为有不同的路径。我想是这样的的EclipseLink莫西( 。元数据在XML中指定),但C#

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#.

推荐答案

XmlSerializer的允许你指定的 属性重写 在动态运行。让我们假设你有以下的静态类:

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; }
}

和下面的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);
        }
    }
}

现在,所有剩下的给你是编写可能读取XML文件,其中包含的属性覆盖,并在运行时从它建立 XmlAttributeOverrides 的一个实例,你会喂到 XmlSerializer的构造。

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.

这篇关于XML映射对象,而在C#中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆