Transform an object in a XDocument with xmlns

Olivier Voutat 21 Reputation points
2021-06-30T09:13:09.087+00:00

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...

https://social.msdn.microsoft.com/Forums/vstudio/en-US/d10213d3-4f70-465f-9fa8-d6d8c260913c/adding-a-namespace-to-a-xelement-object?forum=csharpgeneral

C#
C#
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,650 questions
{count} votes

Accepted answer
  1. Viorel 114.7K Reputation points
    2021-06-30T12:59:43.36+00:00

    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,621 Reputation points
    2021-07-01T07:02:29.483+00:00

    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