【问题标题】:Information from xml to csv从 xml 到 csv 的信息
【发布时间】:2021-04-22 06:53:39
【问题描述】:

我想从 xml 文件中获取信息并将其插入到文件 csv 中。

我在这个论坛的帮助下编写代码:

using System;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
                XNamespace dc = "http://purl.org/dc/elements/1.1/";
                XDocument doc = XDocument.Load("C:\\Users\\Mateusz\\Desktop\\DublinCore.xml");
                var authors = doc.Descendants(dc + "subject");
                foreach (var author in authors)
                {
                    Console.WriteLine(author.Value);
                }
                Console.ReadLine();
            
        }
    }
}

现在这段代码从 1 个文件中获取信息,但是如何从目录中的所有 xml 文件中获取信息呢? 我想我应该使用 for/while 从第一个文件中获取信息,然后从下一个文件中获取信息,但我不知道如何使用 Xdoucment.Load,因为它只针对 1 个文件。

【问题讨论】:

  • 使用Directry.GetFiles或Directory.EnumerateFiles遍历目录中的所有文件,并在每个文件上使用Load。

标签: c# xml csv


【解决方案1】:

尝试以下:

        const string Folder = @"C:\Users\Mateusz\Desktop";
        static void Main(string[] args)
        {
            foreach(string filename in Directory.GetFiles(Folder,"*.xml"))
            {
                XDocument doc = XDocument.Load(filename);
                XNamespace dc = doc.Root.GetNamespaceOfPrefix("dc");
                var authors = doc.Descendants(dc + "subject");
                foreach (var author in authors)
                {
                    Console.WriteLine(author.Value);
                }
                Console.ReadLine();
            }
            
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    • 2014-08-03
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多