You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中从字符串拆分日期并写入XML?

在C#中提取日期并写入XML的实现方案

一、提取日期:正则表达式匹配

你的所有日期格式都是dd.MM.yyyy,可以用正则表达式直接匹配出所有符合该格式的字符串,不管中间的分隔符是+、/还是附带的时间信息。

示例代码:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public static List<string> ExtractDates(string input)
{
    // 匹配dd.MM.yyyy格式的日期
    string pattern = @"\b\d{2}\.\d{2}\.\d{4}\b";
    MatchCollection matches = Regex.Matches(input, pattern);
    
    List<string> dates = new List<string>();
    foreach (Match match in matches)
    {
        dates.Add(match.Value);
    }
    return dates;
}

测试不同输入的效果:

  • 输入19.11.2022 /20.11.2022 + 17.12.2022 /18.12.2022 + 14.01.2023 /15.01.2023 + 11.02.2023 /12.02.2023 + 12.03.2023 + 23.04.2023,会提取出所有8个日期。
  • 输入15.01.2023 (13:30 - 15:00 Uhr),会提取出15.01.2023。
  • 输入04.03.2023 + 05.03.2023,会提取出两个日期。

二、写入XML

用XDocument(LINQ to XML)可以简洁地生成XML文件,步骤如下:

  1. 引用命名空间:using System.Xml.Linq;
  2. 编写写入方法:
public static void WriteDatesToXml(List<string> dates, string outputPath)
{
    XDocument doc = new XDocument(
        new XDeclaration("1.0", "utf-8", "yes"),
        new XElement("Dates",
            from date in dates
            select new XElement("Date", date)
        )
    );
    doc.Save(outputPath);
}

三、完整调用示例

public static void Main()
{
    // 示例输入
    string input1 = "19.11.2022 /20.11.2022 + 17.12.2022 /18.12.2022 + 14.01.2023 /15.01.2023 + 11.02.2023 /12.02.2023 + 12.03.2023 + 23.04.2023";
    string input2 = "15.01.2023 (13:30 - 15:00 Uhr)";
    string input3 = "04.03.2023 + 05.03.2023";
    
    // 提取日期
    List<string> dates1 = ExtractDates(input1);
    List<string> dates2 = ExtractDates(input2);
    List<string> dates3 = ExtractDates(input3);
    
    // 写入XML
    WriteDatesToXml(dates1, "dates1.xml");
    WriteDatesToXml(dates2, "dates2.xml");
    WriteDatesToXml(dates3, "dates3.xml");
}

生成的XML示例(以input3为例):

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Dates>
  <Date>04.03.2023</Date>
  <Date>05.03.2023</Date>
</Dates>

内容的提问来源于stack exchange,提问作者Julian2005

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:10:31