I have some xml that is provided with generic attributes (name, type, etc), where the value of the attribute needs to be the property into which the xml is deserialized.
A sample of the type of xml I’m trying to push onto a class would be:
<root>
<company>
<location>USA</location>
<name>TopCars</name>
</company>
<CarList name="CarCounts">
<ModelList name="Models">
<Column name="Ford">50</Column>
<Column name="Chevy">65</Column>
<Column name="Dodge">75</Column>
</ModelList>
</CarList>
</root>
I can provide some sample code I’ve used, but it doesn’t work and I’d like some fresh outlooks. I was using an xmlReader deserialized by a class that had a single property identified by the attribute “name” which isn’t what I want anyhow. I ultimately want like Class Models which contains Ford, Chevy, and Dodge properties (this is a made up example if you object to the car structure here).
XSD spits out something like this which is kind of what I would expect, but not really what I want:
[...]
<xs:element name="Column" nillable="true" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:simpleContent msdata:ColumnName="Column_Text" msdata:Ordinal="1">
<xs:extension base="xs:string">
<xs:attribute name="name" type="xs:string" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
[...]
I’m not constrained by this technique. I’m developing in C#.
Any help is appreciated.
@RichardTowers: I tried the following with the xml listed and received the error “There is an error in XML document (1, 2).”
Base.Root[] cars = null;
XmlSerializer serializer = new XmlSerializer(typeof(Base.Root[]));
XmlReader reader = XmlReader.Create(new StringReader(xml));
cars = (Base.Root[])serializer.Deserialize(reader);
reader.Close();
I have tried changing the classes you suggested with xmlElementAttribute decorators, adding “” into the beginning of the xmlString. I’ve also tried switching out StringReader with StreamReader to no avail. Any other suggestions?
What you want to do is not really how deserializing works. On the one side you have some XML, on the other a C# class. They need to look like each other for the serializer to do its job.
You say you want a class like:
Firstly, I don’t think its possible to serialize your XML into something like this. But even if it was, what happens if your XML has
Mercedesin instead? You can’t deserialize that bit because it’s not in your class.Basically your classes need to mimic your XML. You want something like:
You can then reference your models by doing something like:
Edit: Here’s a paste with all of the code needed to do this: http://pastebin.com/Z3b3558Z. Sorry about the indentation, VisualStudio got a bit excited.