views:

30

answers:

2

Is it possible to achieve the following in c#...

for the class below...

public class Foo{
 public int BarId{get;set;}
 public string BarString{get;set;}
}

I want to achieve the following XML:

<Foo>
  <BarId BarString="something">123</BarId>
</Foo>
A: 

You should create BarId class which has BarString in it

class BarId
{
    [XmlAttribute]
    public string BarString{get;set;}
}

public class Foo{
 public BarId BarId{get;set;}
}

Or you can use Custom Serialization mechanism like here

ArsenMkrt
how do you get BarId to behave as an int though?
E Rolnicki
You don't. Looks like you'd need programmatic serialization, not attribute-based.
Steven Sudit
I like to stick with the built-in classes where possible. However, custom serializer overrides are not nearly as intimidating as they first appear. There are a number of places where I use them in production code. They permit a great deal of flexibility, especially when matching external or legacy Xml. Even if you're 99% happy with XmlSerializer, its still worth checking out overrides.
TechNeilogy
@Tech: Good advice. I'll also toss in the idea that `XmlSerializer` is more or less obsolete due to the WCF `DataContract` attribute.
Steven Sudit
re:WCF, etc. I agree, @Tech, especially if starting a new project, it's worth looking into some of the more recent serialization technologies beyond XmlSerializer.
TechNeilogy
+1  A: 

ArsenMkrt is on the right track, but is missing the content of the element, I suggest a revised version:

class BarId
{
    [XmlText()]
    public int Content {get; set;}

    [XmlAttribute()]
    public string BarString {get; set;}
}

public class Foo{
    public BarId BarId {get; set;}
}

This way you get the content as an integer.

reSPAWNed