I have this XML document:
<aaa>
<x1></x1>
<x2></x2>
<x3></x3>
</aaa>
And need to convert it to this document:
<aaa>
<bbb note="moved to new">
<x1></x1>
<x2></x2>
<x3></x3>
</bbb>
</aaa>
Using Linq-to-XML, what would be the right code to add all child nodes of to a new descendant , but only if descendant does not exist? I started with this
var docRaw = XElement.Parse( documentString );
var bbbElem = docRaw.Elements( "aaa" ).Where( docRaw => !docRaw.Elements( "bbb" ).Any() );
But I think that takes me down the wrong strategy-path.
All ideas appreciated, thanks.
You can use ReplaceNodes()
to replace the content of the root element. You can replace them with a new node named <bbb>
that contains the root's former child elements.
doc.Root.ReplaceNodes(
new XElement("bbb",
new XAttribute("note", "moved to new"),
doc.Root.Elements()
)
);
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.