2

I've seen similar questions on SO about this, but this is specifically about RestSharp XmlSerializer.

I want this:

<Item>
    ...
</Item>
<Item>
    ...
</Item>
<Item>
    ...
</Item>
<Item>
    ...
</Item>

I have this:

public class MyPoco
{
    [SerializeAs( Name = "Item")
    public List<Item> Items { get; set; }
}

public class Item
{
    ...
}

What I'm getting is this:

<Item>
    <Item>
        ...
    </Item>
    <Item>
        ...
    </Item>
    <Item>
        ...
    </Item>
</Item>

How do I get rid of the parent element when using RestSharp?

autonomatt
  • 4,393
  • 4
  • 27
  • 36
  • 1
    Just a side note: an XML document must have exactly one root element, i.e. what you want is not strictly valid XML. I don't know about RestSharp, but perhaps it won't allow rendering invalid XML. – Christoffer Nov 01 '12 at 10:49
  • 1
    To be clear this is just the xml fragment I've posted. There is of course one root element. – autonomatt Nov 01 '12 at 11:11

2 Answers2

2

Change SerializeAs to XmlElement:

[XmlElement("Item")]
public List<Item> Items { get; set; }

Then tell RestSharp to use the .NET serializer:

 var request = new RestRequest
 {              
     XmlSerializer = new RestSharp.Serializers.DotNetXmlSerializer(),
 };

This will output your list of Items without the parent Item node

James Clay
  • 31
  • 5
1

That will help:

public class MyPoco : List<Item> {}

public class Item { ... }
Alexander Danilov
  • 3,038
  • 1
  • 30
  • 35
  • Inheriting from list is not reccomended. See [this stackoverflow question](https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt) – Almenon Jun 06 '18 at 02:31
  • @Almenon why it is not recommended in this case? You should read your link better. – Alexander Danilov Jun 06 '18 at 10:51
  • I did read it. But you're right, I should be more specific. Inheriting from a list is not reccomended for buisiness objects, but if it is a mechanism then that is fine. – Almenon Jun 10 '18 at 20:53