简体   繁体   English

替换XDocument中的根节点

[英]Replace the root node in XDocument

Is it possible to replace the root element of an XDocument? 是否可以替换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.Root.Name替换名称,但是我被困在看看是否有办法替换整个元素?

最简单的选择是使用新的根目录创建一个新的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. 考虑将其标记为重复项,但您专门询问XDocument,而该问题不是专门询问,但答案使用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 更改XML根元素名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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