5

If my XML is like this:

<Item>
    <Name>Jerry</Name>
    <Array>
        <Item>
            <Name>Joe</Name>
        </Item>
        <Item>
            <Name>Sam</Name>
        </Item>
    </Array>
</Item>

I can serialize it into this class:

[DataContract(Namespace = "", Name = "dict")]
public class Item
{
    [DataMember(Name = "Name")]
    public string Name { get; set; }
    [DataMember(Name = "Array")]
    public IEnumerable<Item> Children { get; set; }
}

But what if my XML is like this?

<Item>
    <Name>Jerry</Name>
    <Item>
        <Name>Joe</Name>
    </Item>
    <Item>
        <Name>Sam</Name>
    </Item>
</Item>

This does not work:

[DataContract(Namespace = "", Name = "Item")]
public class Item
{
    [DataMember(Name = "Name")]
    public string Name { get; set; }
    [DataMember(Name = "Item")]
    public IEnumerable<Item> Children { get; set; }
}

What is the right way to decorate the class?

Jerry Nixon
  • 31,313
  • 14
  • 117
  • 233

2 Answers2

5

If you want control over xml, then XmlSerializer is the way to go, not DataContractSerializer. The latter simply lacks the fine-grained control that XmlSerializer offers; in this case for things like list/array layout - but even just xml attributes are a problem for DataContractSerializer. Then it is just:

public class Item {
    public string Name { get; set; }
    [XmlElement("Item")]
    public List<Item> Children { get; set; }
}
public class Item {
    public string Name { get; set; }
}

and:

var serializer = new XmlSerializer(typeof(Item));
var item = (Item) serializer.Deserialize(source);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Sorry, I didn't expect that this is on WP7 to matter. But System.Xml.XmlSerializer is not part of WP7, it turns out. Suggestion? – Jerry Nixon Nov 21 '11 at 23:32
  • My main suggestion would be : mention the platform in the question. DCS has problems here, simply. You might have to drop to manual parsing. Does WP7 support LINQ-to-XML? If so, I'd use that. – Marc Gravell Nov 21 '11 at 23:40
  • No, but I can't change my downvote to an upvote unless you edit the question :) – Kyle W Nov 21 '11 at 23:44
  • 2
    `System.Xml.Serialization.XmlSerializer` **is part of WP7**. You need to add a reference to System.Xml.Serialization.dll to be able to use it. – carlosfigueira Nov 22 '11 at 01:16
  • @Jerry please note carlosfigueira's comment that XmlSerializer is available. – Marc Gravell Nov 22 '11 at 06:45
0

Try using CollectionDataContractAttribute Internally you should create a generic list of Items and decorate it as CollectionDataContractAttribute with appropriate parameters.

George Mamaladze
  • 7,593
  • 2
  • 36
  • 52