【问题标题】:C# Linq to XML ElementC# Linq to XML 元素
【发布时间】:2017-04-20 18:45:17
【问题描述】:

解决我似乎无法单步执行元素并将日期值转换为 xml 中的日期时间的问题,然后将日期大于“x”日期的所有元素打印到控制台。 XML 文件相当大,但这里有一个示例。

<DataSet>
   <diffgr:diffgram xmls="">
       <NewDataSet>
          <USER_LOGIN>
              <USER_LOGIN_ID>123</USER_LOGIN_ID>
              <DATE>2017-03-01T16:56:16.59-06:00</<DATE>
          </USER_LOGIN>
          <CONTENT>
              <CONTENT_ID>123</CONTENT_ID>
              <DATE>2017-03-01T16:56:16.59-06:00</<DATE>
          </CONTENT>
              ETC. ETC.
       <NewDataSet>
   </diffgr:diffgram> 
<DataSet>

在我的代码中,我有一个列表,我想通读并输出其中日期大于“某个硬编码日期”的所有元素。我意识到我可以为后代中的每个元素都有一个 foreach 循环,但我希望它是动态的,因为与我的示例相比,必须循环的元素要多得多。这是我当前的代码。这失败并在我的代码中的 where 子句上显示 Null 异常。如果我删除 where 子句,它会打印 .

XDocument doc= XDocument.Load("xmlfile.xml");
DateTime testDate= new DateTime(2017, 03, 01);

IEnumerable<XElement> textSeg=
      from element in doc.Descendants("NewDataSet")
      where (DateTime)element.Element("DATE")>testDate
      select element;

      foreach (XElement element in textSeg)
         {Console.Writeline(element);}

【问题讨论】:

  • this SO 问题的可能重复项。
  • 您似乎有一些没有 DATE 元素的节点?尝试查询您的数据以找到 where element.Element("DATE") == null 或添加 DateTime 演员表,看看哪些节点有问题。

标签: xml linq c#-4.0 xelement


【解决方案1】:

您正试图直接从 USER_LOGIN 元素和 CONTENT 元素中获取 DATE 元素;你需要访问他们的子元素。

(请原谅我使用method syntax over query syntax,这是我更喜欢的)

gist here

var dateElements = doc.Descendants("NewDataSet")

// gather all the child-elements of all NewDataSet elements
.SelectMany(dataSetEle => dataSetEle.Elements())

// filter out child-elements that themselves have no applicable DATE child-elements
.Where(childEle => childEle.Elements()
    .Any(grandChildEle =>
        grandChildEle.Name == "DATE" && (DateTime) grandChildEle > testDate)
);

【讨论】:

  • 感谢您的回复。这仅打印出 DATE 元素,但我希望输出也打印块内的所有其他元素。所以如果日期>测试日期,我想以这种格式打印出来。 1232017-03-01T16:56:16.59-06:00123 2017-03-01T16:56:16.59-06:00 等。等等。
  • 我已更新我的答案以返回包含 DATE 元素的元素,而不是 DATE 元素本身。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多