c# - Linq to Xml 转换列表

标签 c# .net linq linq-to-xml

我无法思考如何在 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/

相关文章:

c# - 请解释此代码中 "default()"的用途

c# - 在 C# 中将多个事件处理程序连接到一个事件的最佳方法?

c# - WCF中MinFreeMemoryPercentageToActivateService的意义是什么?

c# - MySql Linq-实体日期比较

c# - 使用 LINQ 的对象层次结构的深度优先展平集合

c# - 这仍然是适配器模式吗?

c# - 图像在 chrome 和 Firefox 中看起来不同

c# - 如何将波斯日期转换为公历日期?

.net - GetReferencedAssemblies不会返回所有程序集

linq - toPagedList() 顺序不同于 LINQ order by 子句