Skip to main content

Generating XML Root Node having colon - via Serialization

Recently I got a requirement to generate an XML on the fly with some defined schema. I know this requirement looks very simple in first sight, but actually it was not.

The XML which was to be generated was having a very specific format as it was supposed to be the input for some 3rd party tool. So, it means, it should be fully compliant with the prescribed XML node structure. Just have a look at the below schema:

<sl:RandomWindow xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sl="http://www.ShwetaBlogs.com/Window" xsi:schemaLocation="http://www.ShwetaBlogs.com/Window wwRandomWindow.xsd">
  <Title>First Window</Title>
  <Border>Single</Border>
</sl:RandomWindow>

Below are the classes I created for serialization purpose:













By using the XmlElement and XmlAttribute classes I was able to generate most of the required parts of the XML as shown below:







But the only thing which didn’t come up correctly was the root node which is expected to be in the form <sl:RandomWindow>.

So, in order to achieve root node with prefix and colon, I updated the code to:

[XmlRoot("sl:RandomWindow")]
    public class RandomWindow {…}

But alas! It gave me some strange results. It converted the prefix to hexadecimal as shown below:







Then I thought, instead of providing concrete prefix, let’s add namespace itself as shown below:
[XmlRoot("RandomWindow", Namespace = "http://www.ShwetaBlogs.com/Window")]
     public class RandomWindow { ... }

And my result was:







Which was bit closer to what I need, but not the exact one. Now the issue remaining was the extra prefix in front of each element :(.

In order to resolve this issue, I tried various options provided over various blogs, but no luck.

But after spending hours, I was able to crack it by hit and try. To hide namespaces at element node level, I provided the namespace value as empty as shown below:















And that did the trick for me. Finally, I was able to achieve the required format.







Although this issue was pretending to be very small, it ate up my so much time. So, thought to share it here. Hope it would be helpful for you too.

Happy troubleshooting !!!

Comments