I am having trouble wrapping my mind around how to do this in linq.
How can i convert this:
<mytags>
开发者_StackOverflow中文版 <tag1>hello</tag1>
<tag2>hello</tag2>
<tag1>MissingTag</tag1>
<tag1>Goodbye</tag1>
<tag2>Goodbye</tag2>
</mytags>
to this
List<MyObject>
public class MyObject
{
public tag1;
public tag2;
}
Try this out:
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, not the other way around.
精彩评论