LINQ到XML可选元素查询 [英] LINQ to XML optional element query

查看:100
本文介绍了LINQ到XML可选元素查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和具有结构(部分)现有的XML文档的工作,像这样:

I'm working with an existing XML document which has a structure (in part) like so:

<Group>
    <Entry>
        <Name> Bob </Name>
        <ID> 1 </ID>
    </Entry>
    <Entry>
        <Name> Larry </Name>
    </Entry>
</Group>



我使用LINQ to XML查询的XDocument检索所有这些条目如下:

I'm using LINQ to XML to query the XDocument to retrieve all these entries as follows:

var items = from g in xDocument.Root.Descendants("Group").Elements("Entry")
    select new
    {
        name = (string)g.element("Name").Value,
        id = g.Elements("ID").Count() > 0 ? (string)g.Element("ID").Value : "none"
    };



在ID元素并不总是存在,因此我的解决方案,这是伯爵()爵士之上。但我不知道是否有人有更好的方式来做到这一点。我仍然获得舒适与这个新的东西,我怀疑有可能是一个更好的方式来做到这一点比我现在怎么做。

The "ID" elements aren't always there and so my solution to this was the Count() jazz above. But I'm wondering if someone has a better way to do this. I'm still getting comfortable with this new stuff and I suspect that there may be a better way to do this than how I'm currently doing it.

有没有更好/更优选的方法做我想要什么?

Is there a better/more preferred way to do what I want?

推荐答案

XElement 实际上具有的有趣的显式转换操作符那些在这种情况下,正确的事情。

XElement actually has interesting explicit conversion operators that do the right thing in this case.

所以,你实际上很少需要访问 .value的属性

So, you rarely actually need to access the .Value property.

这是所有你需要为你的投影:

This is all you need for your projection:

var items =
    from g in xDocument.Root.Descendants("Group").Elements("Entry")
    select new
    {
        name = (string) g.Element("Name"),
        id = (string) g.Element("ID") ?? "none",
    };



如果你愿意使用 ID 作为您的匿名类型的整数:在xDocument.Root

And if you'd prefer to use the value of ID as an integer in your anonymous type:

var items =
    from g in xDocument.Root.Descendants("Group").Elements("Entry")
    select new
    {
        name = (string) g.Element("Name"),
        id = (int?) g.Element("ID"),
    };

这篇关于LINQ到XML可选元素查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆