XML Deserialization
Hi, I want to deserialize an XML document and I'm using an XmlSerializer. That's all fine, but the order of the elements in the XML is important to me.
For example, I might have some xml that looks like:
Where the title and header order is important to me. Is there any way to pull out the "index" of the xml tag when deserializing?
14 Replies
The
[XmlElement]
attribute has an Order
property, IIRC
So
But that would be for serializing it. I just want to deserialize it with the same order as the input xml. i.e. if I had something like:
If you deserialize to a
Book
the order does not matter
You never ever have to care about order of properties in a classThis is a made up case. I'm actually deserializing the XML used to generate a PDF document, where the order does matter
The order of properties is as it is declared in the class
Sort of like as thought I was deserializing HTML
I do in this case 🙂 not the order of the properties in the class, but the order that they were in the original XML
So the order can vary?
yeah
and is important
because the order is how is it displayed in a UI
Aight, that changes things
That is very not xml like
I think you'd have to use a custom deserializer
I know, but it is what I have to work with
I was originally working with something like xElement.Elements().Select(o => {
new { Node = o.Node, Index = o.Index }) etc but's getting complicated!
(big "XML")
Try something like this?
Can your book have multiple titles and headers or only one of each?
Multiple
Imagine something like
I actually want the index for all XmlElements, not just header and title, so not ideal above
Can node just have a content property that is the of type List<BaseElement>?
I'd start with a class model that you want to actually represent your structure and then ask for help on how to parse the Xml into that structure.
You can fairly easily refactor the code I put above to handle most structures.