Reputation: 513
I have some entities that were generated from a database and I wanted to serialize them to XML. The problem is that some of the entities have column names that are not so user friendly and this is reflected in the fields of the generated entity.
Is there a C# attribute that I could apply to the class fields so that I could add an xml attribute, that contains a friendly-name value, to the xml element itself? For example, using something similar to the XmlAttribute:
public class Book
{
public string Title { get; set; }
[XmlAttribute("friendlyName","International Standard Book Number")]
public string ISBN { get; set; }
}
Should result in something like this when it is serialized:
<Book>
<Title>To Kill a Mockingbird</Title>
<ISBN friendlyName="International Standard Book Number">9780061120084</ISBN>
</Book>
Upvotes: 1
Views: 2742
Reputation: 5189
There is not an attribute that will do that. Its not common to mix element documentation with the xml data. Usually, you want to document your xml schema with an xsd document or some other means.
That being said, here is how you could do it. You'd need to change the ISBN
property from a string to a custom type that has a friendlyName
property that you can serialize.
public class Book
{
public string Title { get; set; }
public ISBN ISBN { get; set; }
}
public class ISBN
{
[XmlText]
public string value { get; set; }
[XmlAttribute]
public string friendlyName { get; set; }
}
The following will serialize exactly like what you have in your question.
Book b = new Book
{
Title = "To Kill a Mockingbird",
ISBN = new ISBN
{
value = "9780061120084",
friendlyName = "International Standard Book Number",
}
};
UPDATE
OK, another approach would be to create a custom XmlWriter
that can intercept calls made by the serializer to create elements. When an element is being created for an property that you want to add a friendly name to, you can write in your own custom attribute.
public class MyXmlTextWriter : XmlTextWriter
{
public MyXmlTextWriter(TextWriter w)
: base(w)
{
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
base.WriteStartElement(prefix, localName, ns);
switch(localName)
{
case "ISBN":
WriteAttributeString("friendlyName", "International Standard Book Number");
break;
}
}
}
Here is an example of how you would use it (from a console app):
XmlSerializer serializer = new XmlSerializer(typeof(Book));
serializer.Serialize(new MyXmlTextWriter(Console.Out), b);
You can implement the other constructors of XmlTextWriter
, if you need to be able to write to other things like a Stream
.
Upvotes: 1
Reputation: 34421
Try this
[XmlRoot("Book")]
public class Book
{
[XmlElement("Title")]
public string Title { get; set; }
[XmlElement("ISBN")]
public ISBN isbn { get; set; }
}
[XmlRoot("ISBN")]
public class ISBN
{
[XmlAttribute("friendlyName")]
public string friendlyName { get; set; }
[XmlText]
public string value { get; set; }
}
Upvotes: 0