.net - Add friendly name attribute to xml element using c# attribute for serialization? -


i have entities generated database , wanted serialize them xml. problem of entities have column names not user friendly , reflected in fields of generated entity.

is there c# attribute apply class fields add xml attribute, contains friendly-name value, xml element itself? example, using similar xmlattribute:

public class book {     public string title { get; set; }      [xmlattribute("friendlyname","international standard book number")]     public string isbn { get; set; } }  

should result in when serialized:

<book>   <title>to kill mockingbird</title>   <isbn friendlyname="international standard book number">9780061120084</isbn> </book> 

there not attribute that. not common mix element documentation xml data. usually, want document xml schema xsd document or other means.

that being said, here how it. you'd need change isbn property string custom type has friendlyname property 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 serialize have in question.

book b = new book {     title = "to kill mockingbird",     isbn = new isbn     {         value = "9780061120084",         friendlyname = "international standard book number",     } }; 

update

ok, approach create custom xmlwriter can intercept calls made serializer create elements. when element being created property want add friendly name to, can write in 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 example of how use (from console app):

xmlserializer serializer = new xmlserializer(typeof(book)); serializer.serialize(new myxmltextwriter(console.out), b); 

you can implement other constructors of xmltextwriter, if need able write other things stream.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -