【问题标题】:Consuming API XML into csv file C#将 API XML 消费到 csv 文件 C#
【发布时间】:2021-10-13 23:59:28
【问题描述】:

我在 API 中有以下 XML

我希望从标签中读取数据并使用这些值构建一个 CSV 文件。

到目前为止我的代码,

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "https://localhost:5001/api/Scheduler/GetScheduler";

            WebRequest request = WebRequest.Create(url);
            try
            {
                WebResponse response = request.GetResponse();
                using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    XDocument xmlDoc = new XDocument();
                    try
                    {
                        xmlDoc = XDocument.Parse(sr.ReadToEnd());
                        Console.WriteLine(xmlDoc.Root.Element("ORD_NAME").Value);
                    }
                    catch (Exception)
                    {
                        // handle if necessary
                    }
                }
            }
            catch (WebException)
            {
                // handle if necessary    
            }
        }
    }
}

我可以看到正在读取的数据,但是 xmlDoc,但是 xmlDoc.Root.Element("ORD_NAME").Value 为 NULL。 如何从流中获取数据?

谢谢。

【问题讨论】:

  • “行”是“调度程序”元素,不是吗?您的代码似乎根本没有选择它们,因此您宁愿处理 xmlDoc.Root.Elements("Scheduler") 以映射到 CSV 的一行或一行,然后读出每个子元素或仅读出特定的子元素,例如 ORD_NAME 作为值。跨度>
  • 谢谢,xmlDoc.Root.Elements("Scheduler") 为我提供了我想要的值,但我如何获得它们,所以我可以构建一个 csv 文件。我需要在 xmlDoc.Root.Elements("Scheduler") 上进行 foreach 循环吗?

标签: c# xml api


【解决方案1】:

我想你想要例如

            using (var stream = response.GetResponseStream())
            {
                XDocument xmlDoc = XDocument.Load(stream);
                Console.WriteLine(string.Join("\n", from row in xmlDoc.Root.Elements("Scheduler") select string.Join(";", row.Elements().Select(e => e.Value))));
            }

.NET 可能有一些比直接使用 LINQ to XML 更好的 API 来构造 CSV,上面将无法引用值或转义分隔符。

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 2016-06-08
    • 1970-01-01
    相关资源
    最近更新 更多