不知道节点的 LINQ to XML
我有这个 LINQ 查询:
XNamespace ns = NAMESPACE;
var items = (from c in doc.Descendants(ns +"Item")
select new Item
{
Title = c.Element(ns + "ItemAttributes").Element(ns + "Title").Value,
MFR = c.Element(ns + "ItemAttributes").Element(ns + "Manufacturer").Value,
Offer = c.Element(ns + "Offers").Element(ns + "TotalOffers").Value,
Amazon = c.Element(ns + "Offer").Element(ns + "Merchant").Elements(ns + "MerchantId"),
LowPrice = Convert.ToDouble(c.Element(ns + "FormattedPrice").Value),
SalesRank = Convert.ToInt32(c.Element(ns +"SalesRank").Value),
ASIN = c.Element(ns + "ASIN").Value
}).ToList<Item>();
当节点不存在时,它效果很好。例如,它可能没有 MFR 或销售排名。我怎样才能做到这一点,如果它没有相关节点,它会给我一个默认值,或者根本不会让我尝试捕获一项的整个查询。
I have this LINQ query:
XNamespace ns = NAMESPACE;
var items = (from c in doc.Descendants(ns +"Item")
select new Item
{
Title = c.Element(ns + "ItemAttributes").Element(ns + "Title").Value,
MFR = c.Element(ns + "ItemAttributes").Element(ns + "Manufacturer").Value,
Offer = c.Element(ns + "Offers").Element(ns + "TotalOffers").Value,
Amazon = c.Element(ns + "Offer").Element(ns + "Merchant").Elements(ns + "MerchantId"),
LowPrice = Convert.ToDouble(c.Element(ns + "FormattedPrice").Value),
SalesRank = Convert.ToInt32(c.Element(ns +"SalesRank").Value),
ASIN = c.Element(ns + "ASIN").Value
}).ToList<Item>();
It works great expect for when a node is not present. For example it my not have a MFR or a sales rank. How can I make it so if it does not have the node in question, it gives me a default value or at the very doesn't make me try catch my whole query for one item.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,LINQ to XML 不支持这一点。然而,我在我正在从事的一个项目中遇到了同样的混乱,并为 XElement 创建了这个扩展以允许它。也许它可以为你工作:
基本上它只是检查元素是否存在,如果不存在,它返回一个具有相同名称和空值的元素。
As far as I'm aware LINQ to XML doesn't support this. However I ran into this same mess in a project I was working on and created this extension for XElement to allow it. Maybe it could work for you:
Basically it just checks to see if the element exists and if it doesn't it returns one with the same name and an empty value.
您可以使用 XElement 显式转换,例如:
参考:http://msdn.microsoft。 com/en-us/library/bb340386.aspx
You can use XElement Explicit Conversion, e.g.:
Reference: http://msdn.microsoft.com/en-us/library/bb340386.aspx
如果XElement存在,但值为空的问题?即
然后你可以使用 string.IsNullOrEmpty 函数
if the problem that the XElement exists, but the value is blank? i.e.
then you can use the string.IsNullOrEmpty function