Merge xml nodes of same type and display both results in C#

Alpha Beta 41 Reputation points
2021-08-30T11:20:03.763+00:00

I have 2 XML elements(from same XML document) of the looking like this:

<Parent>
  <Child1>contentA</Child1>
  <Child2>contentB</Child2>      
</Parent>

<Parent>
  <Child1>contentC</Child1>
  <Child2>contentD</Child2>
</Parent>

What I have done:

var Data= from Parent in Parent.Elements("Parent").AsEnumerable()
select new
{
Child1=Parent.Elements("Child1").Value,
Child2=Parent.Elements("Child2").Value
}

This above snippet prints twice.

What I need to do is merge the content of the second Parent node with the first Parent node and display both the contents that would look like this:

<Parent>
  <Child1>contentA/contentC</Child1>
  <Child2>contentB/contentD</Child2>      
</Parent>
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,492 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 113.8K Reputation points
    2021-08-30T14:35:36.967+00:00

    Try something like this:

    var parents = Parent.Elements( "Parent" );
    
    var Data = new
    {
     Child1 = string.Join( "/", parents.Elements( "Child1" ).Select( c => c.Value ) ),
     Child2 = string.Join( "/", parents.Elements( "Child2" ).Select( c => c.Value ) )
    };
    

0 additional answers

Sort by: Most helpful