How to serialize XML attributes in a certain order in C#?

Posted on 2006-06-02
Last Modified: 2013-11-19
I'm using XML serialization to write an object to a xml file.  I'm using the following code:

XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add( "xsi",  "");
namespaces.Add( "xyz", "" );

writer = new StreamWriter(filename);
XmlSerializer serializer = new XmlSerializer(myObject.GetType());                        

serializer.Serialize(writer, myObject, namespaces);

My question is this:  I have an attribute (myAttribute1) for my object which I want to appear in a specific order -  before the namespaces like the following:

<?xml version="1.0" encoding="UTF-8"?>
<xyz:MyObject myAttribute1="123" xmlns:xyz="" xmlns:xsi="">

However, when I serialize the object, I get the following:
<xyz:MyObject  xmlns:xyz="" myAttribute1="123" xmlns:xsi="">

Is there any way to force the attribute to appear first, before the namespaces?



Question by:debbyt
    1 Comment
    LVL 37

    Accepted Solution

    No I do not believe there is without writing a custom serializer.

    Of course the real problem here is that attribute order is supposed to be insignificant ... By adding this requirement you may be making you document not compatible.



    Featured Post

    Course: Create Mobile App Prototypes with Adobe XD

    This is a project-based course: we go through all the steps of creating a prototype from start to finish, using all the tools and features currently available in Adobe XD. You can complete the course in less than a day, plus all project files and fonts are included.

    Join & Write a Comment

    Preface In the first article: A Better Website Login System ( I introduced the EE Collaborative Login System and its intended purpose. In this article I will discuss some of the design consideratio…
    I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
    Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    731 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now