Tony Vitabile
Tony Vitabile

Reputation: 8614

Any way to control the order in which the .NET XmlSerializer outputs attributes?

I'm using a library provided by a third party that uses XML to communicate with a device. The root tag has 2 attributes that have to be present. All of the examples in the documentation show these 2 attributes appearing in a particular order.

I've created classes to use with the .NET XmlSerializer class that contain properties marked with the appropriate XmlAttribute attributes. The output of the XmlSerializer for my classes has these two attributes in the reverse order of all of the examples in the documentation.

If I pass the XML generated by my code to the library, I get an error return value. However, just for kicks, I modified the XML & reversed the order of the attributes. Lo & behold, I got an OK return value. The documenation says that the library is written in Ansi C, so I'm pretty sure they're not using the .NET XmlSerializer.

I know that the XML standard says that the order of attribtues is unimportant. I've notified them that their code violates the standard, and hopefully they'll fix it. But in the meantime, I have to make progress on this project. Is there any way I can get the XmlSerializer to output the attributes in the opposite order? Or am I going to have to generate the XML on my own (a giant pain in the patoot)?

At least I can parse the Xml returned to me with the XmlSerializer class & it won't matter what order the attributes are in to my code.

Thanks

Tony

Upvotes: 3

Views: 350

Answers (2)

Tony Vitabile
Tony Vitabile

Reputation: 8614

The library is going to be fixed, so I decided to implement a very quick and dirty fix.

What I had originally done was implement a ToXml() method which returned a string containing the XML emitted by the XmlSerializer. This method was implemented in the abstract base class. What I did was mark this method as virtual & left it alone. Then, in each child class, I implemented an override of the ToXml method that just used string.Format to create the Xml with the attributes in the desired order.

This took about 5 mintues to implement as I pretty much had to just copy & paste the same few lines of code a few times.

This will all go away once they've fixed their parser.

Thanks all.

Tony

Upvotes: 1

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59983

I'm afraid that implementing IXmlSerializable is your only option at this point.

Upvotes: 0

Related Questions