1

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>
E Rolnicki
  • 1,677
  • 2
  • 17
  • 26

2 Answers2

4

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
  • 1,089
  • 14
  • 21
0

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

Community
  • 1
  • 1
Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
  • how do you get BarId to behave as an int though? – E Rolnicki Jul 22 '10 at 13:58
  • You don't. Looks like you'd need programmatic serialization, not attribute-based. – Steven Sudit Jul 22 '10 at 13:59
  • 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 Jul 22 '10 at 14:23
  • 1
    @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 Jul 22 '10 at 14:34
  • 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 Jul 23 '10 at 14:01