1
votes

Is it possible to replace the root element of an XDocument?

I currently have a document that looks like:

<ArrayOfCompletedInvoice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <CompletedInvoice>
    <Invoice>1</Invoice>
    ...
  </CompletedInvoice>
</ArrayOfCompletedInvoice>

I want it to look like:

<ns0:CompletedInvoices xmlns:ns0="http://myNamespace">
  <CompletedInvoice>
    <Invoice>1</Invoice>
    ...
  </CompletedInvoice>
</ns0:CompletedInvoices>

I know I can replace the name with XDocument.Root.Name, but I am stuck seeing if there's a way to replace the entire element?

2
Can you create a new XDocument with a new root and simply copy over the first level XElements from your original document? (Not my downvote, btw.) - João Mendes
@JoãoMendes, that may just be the easier way around it I suppose. Also thanks for the non-downvote. :p - KnottytOmo
Cool. I'll add it as an answer, for future searchers. - João Mendes

2 Answers

0
votes

The easiest option would be to create a new XDocument with a new root and simply copy over the first level XElements from your original document.

0
votes

Not my answer but this looks pretty similar. Considered marking as duplicate but you ask specifically about XDocument where this question doesn't ask specifically but the answer uses XDocument. (Basically only adding in case somebody stumbles across this but is looking for more information as well and an example).

Change XML root element name