Replace the root node in XDocument

ⅰ亾dé卋堺 提交于 2019-12-12 05:15:10

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/23935917/replace-the-root-node-in-xdocument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!