Tomek
Tomek

Reputation: 91

Impossible? How to deserialize this using DataContractSerializer?

So I have XML that looks like this:

<a>
    <b c="1" ></b>
    <b c="2" ></b>
    <b c="3" ></b>
    <b c="4" ></b>
</a>

I want to deserialize this on wp7 using DataContractSerializerdo that.

I run across some opinions that it is impossible to do that without some tricks like enclosing this XML in additional tags to push < a > down from the root level.
Is it true?

On your request i'm adding some code

Classes:

[KnownType(typeof(B))]
[DataContract(Namespace = "")]
public class A:List<B>
{
    [DataMember]
    public List<B> B
    {
        List<B> _b = new List<B>();
        get { return _b; }
        set { _b = value; }
    }
}

[DataContract(Namespace = "")]
public class B
{
    [DataMember]
    public string c = "foo";
}

Deserialisation:

var serializer = new DataContractSerializer(typeof(A));
var o = serializer.ReadObject(SomeResponseStream);

And many, many other variations of this.
By the way - this arrangement of classes will be serialized to XML like this:

<a>
    <b>
        <b c="1" ></b>
        <b c="2" ></b>
        <b c="3" ></b>
        <b c="4" ></b>
    </b>
</a>

Notice additional, unwanted level of < b >

Upvotes: 0

Views: 603

Answers (1)

EZI
EZI

Reputation: 15364

As said in comments, Linq2Xml can be a better way to go

string xml = @"
<a>
    <b>
        <b c=""1"" ></b>
        <b c=""2"" ></b>
        <b c=""3"" ></b>
        <b c=""4"" ></b>
    </b>
</a>";

var bs = XDocument.Parse(xml)
                    .Root
                    .Element("b")
                    .Elements("b")
                    .Select(b => new B { c = b.Attribute("c").Value })
                    .ToList();

.

public class B
{
    public string c = "foo";
}

Upvotes: 1

Related Questions