asp.net - Using LINQ to surround all "group" elements with the new element "groups" in C# -


i'm new linq , c# have xml file generated database table. within xml document element called "group", wrap group elements element called "groups".

an extract of 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 struggling 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 appreciated.

one way to:

  1. go through each user element
  2. add new groups element
  3. add existing group new groups element
  4. remove original group element

this approach similar this, provided xml xelement:

foreach (var user in xml.elements("user")) {     user.add(new xelement("groups", user.element("group")));     user.element("group").remove();  } 

if you're using xdocument use xml.root.elements("user") instead.


edit: in response comment, if xml contained multiple numbered groups filter on elements start "group" , same thing.

foreach (var user in xml.elements("user")) {     var groups = user.elements()                      .where(e => e.name.localname.startswith("group"))                      .toarray();      // rename groups     foreach (var group in groups)         group.name = "group";      user.add(new xelement("groups", groups));     groups.remove(); } 

notice used toarray() prevent remove call reevaluating expression, incorrectly remove newly added groups element since matches condition of starting "group." way around change where predicate check name ends digit. it's work prevent accidentally selecting other element may start "group" it's based on knowledge of xml structure.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

android - layout with fragment and framelayout replaced by another fragment and framelayout -