XmlSerializer - Create secondary attributes to base types eg string

64 views Asked by At

Using .net XmlSerializer and the following structure:

public class SomeClass {
   [XmlElement("some-string")]
   public string SomeString { get; set; }
}

I need the above to produce :

<someclass>
  <some-string alt-name="someotherstring">
    StringValue
  </some-string>
</someclass>

But i dont want to have to define types for somestring, some int, somebool, yetanotherstring etc every time i want to add a standard type as a porperty to my classes.

Any way I can override xlement to handle this maybe?

2

There are 2 answers

2
andrei.ciprian On BEST ANSWER

Produce wrappers for base types and conversion operators to alleviate object construction:

[Serializable()]
public partial class StringWrapper
{
    [XmlAttribute("alt-name")] 
    public string altname { get; set; }
    [XmlText()] 
    public string Value { get; set; }

    public static implicit operator string (StringWrapper sw) { return sw.Value; }

    public static implicit operator StringWrapper (string s) { 
      return new StringWrapper() { altname = "someotherstring", Value = s };
    }
}

Use wrappers instead of base types where needed:

[Serializable()]
[XmlRoot(Namespace = "someclass", IsNullable = false)]  
public class someclass
{
    [XmlElement("some-string")] 
    public StringWrapper somestring { get; set; }
}

Use it like:

var srlz = new XmlSerializer(typeof(someclass));
srlz.Serialize(Console.Out, new someclass() { somestring = "StringValue" });
0
Marc Gravell On

The only way to do that via XmlSerializer is:

[XmlRoot("someclass")]
public class SomeClass {
    [XmlElement("some-string")]
    public SomeOtherClass Foo {get;set;}
}
public class SomeOtherClass {
    [XmlText]
    public string Text {get;set;}
    [XmlAttribute("alt-name")]
    public string Bar {get;set;}
}

Alternatively: use XmlDocument / XDocument instead of XmlSerializer.