我无法思考如何在 linq 中执行此操作。
我如何转换它:
<mytags>
<tag1>hello</tag1>
<tag2>hello</tag2>
<tag1>MissingTag</tag1>
<tag1>Goodbye</tag1>
<tag2>Goodbye</tag2>
</mytags>
为此
List<MyObject>
public class MyObject
{
public tag1;
public tag2;
}
最佳答案
试试这个:
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();
这只适用于缺少 tag2 的场景,反之则不行。
关于c# - Linq to Xml 转换列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2170644/