Subscribe via RSS
10May/180

How to convert XML into a class the easy way!

An on-the-side project, that's been going for quite a while now, extracts data from a remote service. For a very long time, this was done via reverse-engineered Java code, of which I then wrapped my own console app around. All worked very well until they changed the login service request format and stopped using the Java altogether.

The new version was just HTML and json and, but the actual payload of the data I cared about was XML. Yes, that's right, XML in a string via JSON. Who would'da thunk? Regardless of the insanity, I was still itching to parse it.

So, the usual Json to C# class generator was used to build the de-serialisable class for the initial packet. I then needed a quick and smart way to convert the XML into a class.

Turns out that there is also an XML to C# converter! Paste in your XML blob and, if correctly formatted, it'll return a class that the XML can be de-serialised into!

And, it worked perfectly. Well, nearly. There was one gotcha! The XML class I was decoding had one field called Text. This is not a valid name inside a deserialised class in C#. So call it a different name in the class but override it via an attribute, as per below.

[XmlRoot(ElementName = "g", Namespace = "http://www.w3.org/2000/svg")]
public class G
{
        [XmlElement(ElementName = "rect", Namespace = "http://www.w3.org/2000/svg")]
        public List<rect> Rect { get; set; }
        [XmlElement(ElementName = "text", Namespace = "http://www.w3.org/2000/svg")]
        public List<textitem> Texts { get; set; }
        [XmlAttribute(AttributeName = "fill")]
        public string Fill { get; set; }
        [XmlAttribute(AttributeName = "stroke")]
        public string Stroke { get; set; }
        [XmlAttribute(AttributeName = "transform")]
        public string Transform { get; set; }
        [XmlAttribute(AttributeName = "text-anchor")]
        public string Textanchor { get; set; }
        [XmlElement(ElementName = "g", Namespace = "http://www.w3.org/2000/svg")]
        public G[] subG { get; set; }
}

Those watching trains on maps in Australia have the above site to thank for the speedy recovery of the service :)

avatar

About stevenh

Trains... trains... trains... + Electronics + Japan.
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


*

No trackbacks yet.