【问题标题】:How to filter an empty XML element using LinQ in WinRT?如何在 WinRT 中使用 LinQ 过滤空 XML 元素?
【发布时间】:2012-06-18 01:43:07
【问题描述】:

我想要什么
检索“到期”元素过期的任务。

什么是 XML

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<tasks>
  <task>    
    <title>11111</title>
    <due>2012/06/18</due>
  </task>
  <task>
    <title>2121211212</title>    
    <due></due>
  </task>
</tasks>

我的代码

        var res = from q in xml.Root.Descendants("task")
                  where q.Element("due").IsEmpty == false & (Convert.ToDateTime(q.Element("due").Value)).Date < DateTime.Now.Date
                  select q

错误是什么

在 mscorlib.dll 中发生了“System.FormatException”类型的异常,但未在用户代码中处理

附加信息:字符串未被识别为有效的日期时间。 如果有这个异常的处理程序,程序可以安全地继续。

-_-
如果我删除元素“到期”为空的任务,错误就消失了。
但是我不只是用下面的代码过滤空元素吗?!

q.Element("due").IsEmpty == false

为什么以及如何解决?

【问题讨论】:

    标签: c# xml linq windows-8 windows-runtime


    【解决方案1】:

    XElement.IsEmpty

    请注意,包含开始和结束标签且标签之间没有内容的元素不被视为空元素。它有没有长度的内容。只有一个只包含一个开始标签的元素,并且表示为一个终止的空元素,才被认为是空的。

    您可以使用string.IsNullOrWhiteSpace 来检查元素是否包含文本字符:

    var res = from q in xml.Root.Descendants("task")
              where q.Element("due").IsEmpty == false &&
                    string.IsNullOrWhiteSpace(q.Element("due").Value) == false &&
                    Convert.ToDateTime(q.Element("due").Value).Date < DateTime.Now.Date
              select q
    

    【讨论】:

      猜你喜欢
      • 2021-07-22
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多