简体   繁体   English

XmlSerializer和修饰的类(C#)

[英]XmlSerializer and decorated classes (C#)

I leveraging the XmlSerializer to convert to/from XML. 我利用XmlSerializer转换为XML。 Here is an example class: 这是一个示例类:

[XmlRootAttribute("myClass")]
public class MyClass {
    private string someField;

    [XmlElement("someField")]
    public string SomeField {
        get {
            return someField;
        }

        set {
            someField = value;
        }
    }
}

The XML would look like the following: XML如下所示:

<myClass>
    <someField>Some Value</someField>
</myClass>

I want to be able to add an attribute to this class. 我希望能够向此类添加属性。 For example, sometimes I need to add change tracking to the element. 例如,有时我需要向元素添加变更跟踪。 An attribute, say "IdRef", would be added to the myClass element. 一个名为“ IdRef”的属性将被添加到myClass元素中。

<myClass t:IdRef="someGuid" xmlns:t="uri:some:uri">
    <someField>SomeValue</someField>
</myClass>

I'm hoping to keep the IdRef attribute out of the main POCO class. 我希望将IdRef属性保留在POCO主类之外。 Also, since there are many classes like the one above, so I'm hoping not to have to create a subclass for each one, adding the extended attribute. 另外,由于有许多类似上面的类,所以我希望不必为每个类创建一个子类,而要添加扩展属性。 Maybe creating a custom implementation using the IXmlSerializer interface? 也许使用IXmlSerializer接口创建自定义实现?

UPDATE I'm going with the simple solution described below. 更新我将使用下面描述的简单解决方案。 I think I was trying to "over think" this implementation and adding complexity where it wasn't needed. 我想我试图“过度考虑”这种实现,并在不需要的地方增加复杂性。

What do I think? 我怎么想 I think you'll have to stick them in your "POCO" class, but you can hide them away in a region labeled something like "extra serialization markup properties" and use other attributes to make them mostly invisible to consumers of your class. 我认为您必须将它们保留在“ POCO”类中,但是您可以将它们隐藏在标有“额外序列化标记属性”之类的区域中,并使用其他属性使它们对您的类的消费者几乎不可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM