Linq to Xml Convert List

I am having trouble figuring out how to do this in linq.

How can I convert this:

<mytags> <tag1>hello</tag1> <tag2>hello</tag2> <tag1>MissingTag</tag1> <tag1>Goodbye</tag1> <tag2>Goodbye</tag2> </mytags> 

to that

 List<MyObject> public class MyObject { public tag1; public tag2; } 
+4
source share
1 answer

Try the following:

 string input = "<mytags><tag1>hello</tag1><tag2>hello</tag2><tag1>MissingTag</tag1><tag1>Goodbye</tag1><tag2>Goodbye</tag2></mytags>"; var xml = XElement.Parse(input); var list = (from x in xml.Elements("tag1") let next = x.NextNode as XElement select new MyObject { Tag1 = x.Value, Tag2 = (next != null && next.Name == "tag2") ? next.Value : "" }).ToList(); 

This only works for scenarios where tag2 is missing, and not vice versa.

+4
source

Source: https://habr.com/ru/post/1299862/


All Articles