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
367 views
in Technique[技术] by (71.8m points)

.net - Ignore field order in DataContractSerializer

When deserializing, DataContractSerializer requires not only that an element name matches, but also that it is in a certain order with respect to the other elements.

My application is such that every field can be uniquely identified by its name. I would therefore like it to be possible for the XML file to contain the elements in any order and for the deserializer to still work.

Is it possible to set up a DataContract like this?

The introductory paragraph in Data Member Order suggests that order is enforced optionally, but I haven't found a way to actually make it optional.

Follow-up question: Simple data file versioning with DataContractSerializer

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

No it's not optional. It's optional to explicitly specify an ordering, but otherwise the order is determined by the basic rules you linked to (base types first, alphabetic, ...).

The introductory paragraph is simply implying that you don't always need to know or care about the order - for example if you are using a generated proxy.

If you're using DataContractSerializer to deserialize a file, the best solution I can think of would be to use XSLT to transform it into the correct order before deserializing.

If you're calling a web service (what DataContractSerializer was designed for), you're better off sticking to the order in the contract.


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

...