Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add attributes for C# XML Serialization

People also ask

What is a attribute in C?

Attributes are a mechanism by which the developer can attach extra information to language entities with a generalized syntax, instead of introducing new syntactic constructs or keywords for each feature.

How do you write a custom attribute?

Creating Custom Attributes (C#)The class name AuthorAttribute is the attribute's name, Author , plus the Attribute suffix. It is derived from System. Attribute , so it is a custom attribute class. The constructor's parameters are the custom attribute's positional parameters.


Where do you have the type stored?

Normally you could have something like:

class Document {
    [XmlAttribute("type")]
    public string Type { get; set; }
    [XmlText]
    public string Name { get; set; }
}


public class _Filter    
{
    [XmlElement("Times")]    
    public _Times Times;    
    [XmlElement("Document")]    
    public Document Document;    
}

The string class doesn't have a type property, so you can't use it to create the desired output. You should create a Document class instead :

public class Document
{
    [XmlText]
    public string Name;

    [XmlAttribute("type")]
    public string Type;
}

And you should change the Document property to type Document


It sounds like you need an extra class:

public class Document
{
    [XmlAttribute("type")]
    public string Type { get; set; }
    [XmlText]
    public string Name { get; set; }
}

Where an instance (in the example) would have Type = "word" and Name = "document name"; documents would be a List<Document>.

By the way - public fields are rarely a good idea...