I’m new to LINQ and C# but I have an xml file generated from a database table. Within the XML document is a element called “group”, I would like to wrap all group elements with the element called “groups”.
An extract of the XML document is:
<members>
- <user>
<fullname>John Smith</fullname>
<username>SmithA</username>
<email>John.smith@test.com/email>
<distinguishedName>xxx</distinguishedName>
<group>London</group>
</user>
- <user>
<fullname>Sue Jones</fullname>
<username>JonesS</username>
<email>Sue.Jones@test.com/email>
<distinguishedName>xxx</distinguishedName>
<group>London</group>
</user>
</members>
The end result I struggling to code in C# ASP.NET is:
<members>
- <user>
<fullname>John Smith</fullname>
<username>SmithA</username>
<email>John.smith@test.com/email>
<distinguishedName>xxx</distinguishedName>
<groups>
<group>London</group>
<groups>
</user>
- <user>
<fullname>Sue Jones</fullname>
<username>JonesS</username>
<email>Sue.Jones@test.com/email>
<distinguishedName>xxx</distinguishedName>
<groups>
<group>London</group>
<groups>
</user>
</members>
Any help will be appreciated.
One way to do this is to:
userelementgroupselementgroupto the newgroupselementgroupelementThis approach would be similar to this, provided
xmlis anXElement:If you’re using an
XDocumentyou could usexml.Root.Elements("user")instead.EDIT: in response to your comment, if the XML contained multiple numbered groups you could filter on all elements that start with “group” and do almost the same thing.
Notice that I used
ToArray()to prevent theRemovecall from reevaluating the expression, which would incorrectly remove the newly addedgroupselement since it too matches the condition of starting with “group.” Another way around this would be to change theWherepredicate to also check that the name ends with a digit. It’s extra work to prevent accidentally selecting any other element that may start with “group” but it’s up to you based on your knowledge of the XML structure.