【问题标题】:maximum DateTime in XMLXML 中的最大日期时间
【发布时间】:2018-06-02 11:17:53
【问题描述】:

我试图在我的 XML 中找到最大的 DateTime 值。

这是一个 XML 示例:

<?xml version="1.0" encoding="utf-16"?>
<?xml-stylesheet type='text/xsl' href='http://127.0.0.123/sitemaps/xmltemplate/main-sitemap.xsl'?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  <url>
    <loc>http://127.0.0.123/?????</loc>
    <lastmod>2018-05-13</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.1</priority>
  </url>
  <url>
    <loc>http://127.0.0.123/?????-????</loc>
    <lastmod>2018-05-26</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.1</priority>
  </url>
</urlset>

这是我尝试使用的代码:

XDocument xdoc = XDocument.Load(FullAddressXML);
var maxId = xdoc.Elements("url").Select(x => new {                
        MaxDateTime = x.Descendants("lastmod").Max(y=>(DateTime)y)
    });

当我运行这个时,maxId 是空的。

【问题讨论】:

  • 请您提供比“它有效”更多的细节吗?编译失败了吗?它会编译但抛出异常吗? (如果是这样,什么异常?)它不会抛出异常,但没有给您期望的答案吗?
  • 编译完成但maxId为空
  • 所以请将该详细信息编辑到问题中。只说“它不起作用”的问题绝不是一个好问题。

标签: c# xml linq-to-xml xelement


【解决方案1】:

这里有三个问题:

  • 您正在调用xdoc.Elements("url"),它永远不会返回任何元素,因为没有url 元素作为文档的直接后代;您希望 xdoc.Root.Elements 在根元素中找到 url 元素
  • 您正在提供元素的 本地名称,但由于默认命名空间,它们实际上位于您未指定的 "http://www.sitemaps.org/schemas/sitemap/0.9" 命名空间中,因此不会查找任何元素
  • 您正在找到一个 序列,其中包含最大 DateTime 值,每个 url 元素一个,这几乎肯定不是您想要做的 - 您可能想要整个 所有个网址。

此外,不清楚为什么要使用单个属性创建新的匿名类型 - 这通常没用。

这是一个适用于您的示例数据的示例:

using System;
using System.Linq;
using System.Xml.Linq;

public class Test
{
    static void Main()
    {
        var doc = XDocument.Load("test.xml");
        XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
        var max = doc.Root
            .Elements(ns + "url")
            .Max(url => (DateTime) url.Element(ns + "lastmod"));
        Console.WriteLine(max);
    }
}

或者,如果永远不会有任何其他 lastmod 元素,您可以在文档本身上使用 Descendants

var max = doc.Descendants(ns + "lastmod").Max(x => (DateTime) x);

【讨论】:

    猜你喜欢
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    相关资源
    最近更新 更多