Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

c# - WCF DataMember List<> without enclosing element

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>?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...