Create C # object based on xml file?

It may be a way out of the left field, crazy, but I just need to ask before I start implementing this massive set of classes.

Basically, I am writing a parser message analyzer that decodes a specific format of a military message into an object. The problem is that there are literally hundreds of different types of messages, and they have almost nothing in common with each other. Thus, I plan to implement this to create hundreds of different objects.

However, although the message attributes have nothing in common, the method for decoding them is quite simple and follows the pattern. Therefore, I plan to write a code generator to generate all objects and decoding logic for each type of message.

That would be very nice if there was some way to dynamically create an object based on some kind of scheme. It doesn't have to be XML, but XML is pretty easy to work with.

Is this possible in C #?

I would like the interface to look something like this:

var decodedMessage = MessageDecoder.Decode(byteArray); 

If MessageDecoder determines what type of message it has, then returns the corresponding object. It will probably return an interface that implements the MessageType property or something like that.

Basically, I am wondering if there is a way to have one object named Message that implements the MessageType property. And then Depending on the type of MessageType, the Message object is converted to any type of message, so I do not need to spend time creating all these types of messages.

+4
source share
3 answers

ExpandOobject Where you can dynamically add fields to an object.

Good starting point here.

+3
source

Is xsd.exe what are you looking for? It can take an XML file or schema and generate C # classes. One of the problems you may encounter is that some formats of military communications are VERY dumb. You can get very large code files.

+2
source

Check out the T4 templates . They allow you to write code to generate code, they are integrated into the IDE, and they are quite lightweight in fact.

EDIT: There is no way to do what you need with var , because var requires the right side of the job to be statically typed (at compile time). I suppose you could dynamically generate this statement, then compile and run it, but this is a very painful approach.

If you have an XSD for all message types, you can use xsd.exe , as @jle suggests. If not, then I am interested to know the following:

 // Let assume this works var decodedMessage = MessageDecoder.Decode(byteArray); // Now what? I don't know what properties there are on decodedMessage, so I cant do anything with it. 
+1
source

Source: https://habr.com/ru/post/1402537/


All Articles