Transform an object in a XDocument with xmlns

Olivier Voutat 21 Reputation points

Actually I transform an object to a XDocument with this function

public XDocument ToXDocument()
         var xDocSerialized = new XDocument();
         using (var writer = xDocSerialized.CreateWriter())
                  var serializer = new XmlSerializer(this.GetType(), new XmlRootAttribute("PrintRequest"));
                  serializer.Serialize(writer, this);
         return xDocSerialized;

It is possible to add a xmlns in the process ?

I found this page, but it means cloning all XDocument again...

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,192 questions
{count} votes

Accepted answer
  1. Viorel 111.7K Reputation points

    Try this:

    var serializer = new XmlSerializer( this.GetType(), null, null, new XmlRootAttribute( "PrintRequest" ), "my namespace..." );
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,611 Reputation points

    Hi @Olivier Voutat ,
    You can also change the namespace of the root element via following code:

    XNamespace xmlns = "your XNamespace string";  
    XDocument.Root.Name = xmlns + XDocument.Root.Name.LocalName;  

    More details please refer to this thread.
    Best Regards,
    Daniel Zhang

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments