3

The following DataContract:

    [DataContract(Namespace = "http://namespace", Name = "Blarg")]
    public class Blarg
    {
        [XmlAttribute("Attribute")]
        public string Attribute{ get; set; }

        [DataMember(Name = "Record", IsRequired = false, Order = 4)]
        public List<Record> Record{ get; set; }
    }

Serializes into this:

<Blarg Attribute="blah">
    <Record>
        <Record/>
        <Record/>
        <Record/>
    </Record>
</Blarg>

But I want this:

<Blarg>
    <Record/>
    <Record/>
    <Record/>
<Blarg/>

The DataContractSerializer seems to be inserting the header parent automagically and I don't want it.

How do I go about removing the wrapping <Record>?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Ryan
  • 31
  • 1
  • 2
  • 2
    Why are you using "`XmlAttribute`"? the Data Contract Serializer never uses attributes. – John Saunders Jul 16 '10 at 18:26
  • The XmlAttribute Serializes without any issues throguh the DataContract Serilaizer - bu that not the issue I am having. – Ryan Jul 16 '10 at 18:30
  • 1
    it doesn't serialize as an attribute, though, which is what it's `XmlAttribute` is intended for. I recommend you remove it and see what happens. – John Saunders Jul 16 '10 at 18:40

2 Answers2

2

I don't think you can do that.

The DataContractSerializer is optimized for speed, and in the process it sacrifices some flexibility and some features (like XML attributes). I don't think you have much chance to influence the DCS - it does its job as it sees fit, and as quickly as possible. You get to define quite neatly what to serialize (with the [DataMember] attribute, but you don't really have a say in how to serialize.

If you need more control, you could pick the XmlSerializer instead - in that case, you have 10-15% slower serialization, but you can control things like the shape of the data etc. But even in this case - I am not aware of any way you can tell the XML serializer to serialize a collection into a series of XML tags without an enclosing tag for the collection.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I switched to XmlSerializer and was able to remove the enclosing tag. Thanks for your help! – Ryan Jul 19 '10 at 12:04
  • 3
    @Ryan: care to share **how** you did this?? You can answer your own question with that solution - would be useful to someone, someday, maybe. – marc_s Jul 20 '10 at 04:52
0

I found the answer here. See the short story bellow(for the long one checkout the url):

 [XmlElement ("Parameter")]
    public List<Parameter> Parameters;
Bianca
  • 382
  • 4
  • 12