问题
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 XElement
s 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