2

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.

1 Answer 1

3

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" />
Sign up to request clarification or add additional context in comments.

1 Comment

A bit belated but thank-you @VirtualBlackFox. It worked - many thanks for your response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.