question

OlivierVoutat-2267 avatar image
0 Votes"
OlivierVoutat-2267 asked OlivierVoutat-2267 commented

Transform an object in a XDocument with xmlns

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







dotnet-csharp
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.


What output do you expect, just the 'xmlns="..."' attribute to root node?


0 Votes 0 ·

yes, exactly

0 Votes 0 ·
Viorel-1 avatar image
1 Vote"
Viorel-1 answered OlivierVoutat-2267 commented

Try this:

 var serializer = new XmlSerializer( this.GetType(), null, null, new XmlRootAttribute( "PrintRequest" ), "my namespace..." );



· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Works perfectly @Viorel-1

Thank you very much.

0 Votes 0 ·
DanielZhang-MSFT avatar image
0 Votes"
DanielZhang-MSFT answered

Hi @OlivierVoutat-2267,
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.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.