Bastien
Bastien

Reputation: 1013

XmlSerializer deserialize attribute of empty elements

I have a problem with my XmlSerializer. I try to deserialize this file :

<MyClass Id="12">
    <ProblemHere Value="8"/>
    <OtherElement>0</OtherElement>
    <fdp>NTM</fdp>
</MyClass>

in this class :

[XmlType(TypeName = "MyClass")]
public class MyClass
{
    [XmlAttribute(AttributeName = "Id")]
    public int Id { get; set; }

    //Here I try somes head but it's a failure
    public int ProblemHere { get; set; }

    public int OtherElement{ get; set; }

    public string fdp{get; set}
}

As you may understand, what I want is to set ProblemHere to its value (8 here). Is there any simple way to do that or do I have to create a ProblemHere class with an int Value property (seems like an overkill to me) ?

Upvotes: 1

Views: 584

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062620

Yes, you have to create a class to represent that aspec of the data, i.e.

public class Foo {
    [XmlAttribute]
    public int Value {get;set;}
}

public Foo ProblemHere { get; set; }

That is the only way XmlSerializer will work with the structure you want.

Upvotes: 1

Matthew Flynn
Matthew Flynn

Reputation: 3931

you could do something like this

private int _problem = 0;
public int ProblemHere { get {return _problem; }  set { _problem = value; } }

not pretty but works

Upvotes: 0

Arno Peters
Arno Peters

Reputation: 675

As far as I know you have to create a separate class. The property is named "ProblemHere", but you want the attribute to be named "value" - I do not know of any attributes in .Net that can do this.

I usually prefer to have visual studio generate a base XSD (which I can tweak later), and then use xsd.exe to generate a set of (de)serialization classes for it.

Upvotes: 1

Related Questions