string myTagData = “some valid xml data”;
I want to write the LINQ to XML Query that can convert XML1 and XML2 to resultant XML1 and resultant XML2 , if abc tag exists then insert the content of myTagData as last child of abc tag otherwise if abc tag doesn’t exist add myTagData content as last child of Root Element.
XML1
<data>
<abc>
<tag1></tag1>
<tag2></tag2>
</abc>
</data>
XML2
<data>
<data>
<cde>
</cde>
<xyz>
</xyz>
</data>
Resultant xml 1
<data>
<abc>
<tag1></tag1>
<tag2></tag2>
<myTag></myTag>
</abc>
<bcd>
</bcd>
</data>
Resultant XML2
<data>
<cde>
</cde>
<xyz>
</xyz>
<myTag></myTag>
</data>
That’s easy. Assuming you’ve got a variable
datarepresenting the<data>element, andmyTagDatais an element you want to add:That’s using the null-coalescing operator as an easy way of switching between the two options… because the
Elementmethod returns null if the requested element doesn’t exist. If you’re not comfortable with the null-coalescing operator, you may find this simpler to understand:Personally I refer the concise version though 🙂