Search code examples
xmlvb.netxmlwriter

Write xmlns element with attributes


I'm using XmlWriter to generate an XML file. I am trying to replicate an old XML file and I want to create an entry that will look like;

<Return xmlns="http://address/here" appName="Data Return - Collection Tool" appVer="1.1.0">

My code is as follows:

        writer.WriteStartElement("Return", "http://address/here")
        writer.WriteAttributeString("appName", "Data Return - Collection Tool")
        writer.WriteAttributeString("appVer", "1.1.0")

This is generating the attributes in the wrong order ie.

<Return appName="Data Return - Collection Tool" appVer="1.1.0" xmlns="http://address/here">

How can i get these to appear in the order i want. Any help please.


Solution

  • XmlWriter allow you to write the xmlns attribute when you want if the value is the same than the one specified in WriteStartElement :

    void Main()
    {
        StringWriter stringWriter = new StringWriter();
        using(XmlWriter writer = XmlWriter.Create(stringWriter))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("Return", "http://address/here");
            writer.WriteAttributeString("xmlns", "http://address/here");
            writer.WriteAttributeString("appName", "Data Return - Collection Tool");
            writer.WriteAttributeString("appVer", "1.1.0");
            writer.WriteEndElement();
            writer.WriteEndDocument();
        }
    
        Console.WriteLine(stringWriter.ToString());
    }
    

    Output :

    <Return xmlns="http://address/here" appName="Data Return - Collection Tool" appVer="1.1.0" />