简体   繁体   中英

Replace the root node in XDocument

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?

最简单的选择是使用新的根目录创建一个新的XDocument ,然后从原始文档中复制第一级XElement

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM