locked
Combining two Elements in XML document RRS feed

  • Question

  • Hello,

    I have a simple question - for those who have used LINQ to XML much... How can I combine to Elements as one?

    E.g.

    <Root>

       <ChildOne>Value X</ChildOne>

       <ChildTwo>Value Y</ChildTwo>

       <ChildOne>Value 1</ChildOne>

       <ChildTwo>Value 2</ChildTwo>

    </Root>

    into this:

    <Root>

       <Child>Value X Value Y</Child>

       <Child>Value 1 Value 2</Child>

    </Root>

    Thanks

    Mick

    Monday, November 16, 2015 4:44 PM

Answers

  • Here it is...

    XElement root = XElement.Parse(@"<Root>
       <ChildOne>Value X</ChildOne>
       <ChildTwo>Value Y</ChildTwo>
       <ChildOne>Value 1</ChildOne>
       <ChildTwo>Value 2</ChildTwo>
    </Root>");
    
    XElement xmlNew = new XElement("Root",
    	new XElement("Child", 
    		root.Elements("ChildOne").ElementAt(0).Value +" "+ root.Elements("ChildTwo").ElementAt(0).Value),
    	new XElement("Child", 
    		root.Elements("ChildOne").ElementAt(1).Value +" "+root.Elements("ChildTwo").ElementAt(1).Value));

    xmlNew will contain the desired structure:

    <Root>
      <Child>Value X Value Y</Child>
      <Child>Value 1 Value 2</Child>
    </Root>
    

    • Marked as answer by Mick000001 Monday, November 16, 2015 8:47 PM
    Monday, November 16, 2015 8:27 PM

All replies

  • Here it is...

    XElement root = XElement.Parse(@"<Root>
       <ChildOne>Value X</ChildOne>
       <ChildTwo>Value Y</ChildTwo>
       <ChildOne>Value 1</ChildOne>
       <ChildTwo>Value 2</ChildTwo>
    </Root>");
    
    XElement xmlNew = new XElement("Root",
    	new XElement("Child", 
    		root.Elements("ChildOne").ElementAt(0).Value +" "+ root.Elements("ChildTwo").ElementAt(0).Value),
    	new XElement("Child", 
    		root.Elements("ChildOne").ElementAt(1).Value +" "+root.Elements("ChildTwo").ElementAt(1).Value));

    xmlNew will contain the desired structure:

    <Root>
      <Child>Value X Value Y</Child>
      <Child>Value 1 Value 2</Child>
    </Root>
    

    • Marked as answer by Mick000001 Monday, November 16, 2015 8:47 PM
    Monday, November 16, 2015 8:27 PM
  • Yep, thats the one. Thanks.

    I finally got it done using one foreach but this seems better.

    Mick


    • Edited by Mick000001 Monday, November 16, 2015 8:48 PM
    Monday, November 16, 2015 8:47 PM