循环使用C#将XML文件存储到CSV中

时间:2021-10-13 14:31:09

In my Project I am using a time log api, which includes a long XML file including emplyee id, name, company name, id etc. Now I want to store that XML properties into a CSV file with heading of that propertyname. For example Emaployee name, Employee id,etc. With my code I the looping of the XML file is now working. It gives all error messages, sometimes one value in more times.

在我的项目中,我使用时间日志api,其中包括一个长XML文件,包括emplyee id,名称,公司名称,id等。现在我想将这些XML属性存储到带有该属性名称标题的CSV文件中。例如Emaployee名称,员工ID等。使用我的代码,我现在正在循环使用XML文件。它提供所有错误消息,有时一次更多次。

The XML file of my Project

我的项目的XML文件

     <?xml version="1.0" encoding="utf-8"?>
<tlp:WorkUnits xmlns:tlp="http://www.timelog.com/XML/Schema/tlp/v4_4"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.timelog.com/XML/Schema/tlp/v4_4 http://www.timelog.com/api/xsd/WorkUnitsRaw.xsd">
  <tlp:WorkUnit ID="130">
    <tlp:EmployeeID>3</tlp:EmployeeID>
    <tlp:AllocationID>114</tlp:AllocationID>
    <tlp:TaskID>239</tlp:TaskID>
    <tlp:ProjectID>26</tlp:ProjectID>
    <tlp:ProjectName>LIK Template</tlp:ProjectName>  
  </tlp:WorkUnit>

I have A workunit Class where I the properties are declared for XML.

我有一个workunit类,其中我为XML声明了属性。

Now I create a class where I want to loop through the XML and store that file into CSv, But nothing is showing properly.

现在我创建一个类,我想循环遍历XML并将该文件存储到CSv中,但没有任何正确显示。

Here is that class

这是上课

    namespace TimeLog.ApiConsoleApp
{
    /// <summary>
    /// Template class for consuming the reporting API
    /// </summary>
    public class ConsumeReportingApi
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(ConsumeReportingApi));

        public static void Consume()
        {
            if (ServiceHandler.Instance.TryAuthenticate())
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Successfully authenticated on reporting API");
                }

                var customersRaw = ServiceHandler.Instance.Client.GetWorkUnitsRaw(ServiceHandler.Instance.SiteCode,
                     ServiceHandler.Instance.ApiId,
                     ServiceHandler.Instance.ApiPassword,

                  );



                if (customersRaw.OwnerDocument != null)
                {
                     var namespaceManager = new XmlNamespaceManager(customersRaw.OwnerDocument.NameTable);
                namespaceManager.AddNamespace("tlp", "http://www.timelog.com/XML/Schema/tlp/v4_4");
                var workUnit = customersRaw.SelectNodes("tlp:WorkUnit", namespaceManager);


                    if (workUnit != null)
                    {
                        var output = new StringBuilder();
                        foreach (XmlNode customer in workUnit)
                        {
                            var unit = new WorkUnit();
                            var childNodes = customer.SelectNodes("./*");

                            if (childNodes != null)
                            {
                                foreach (XmlNode childNode in childNodes)
                                {
                                    if (childNode.Name == "tlp:EmployeeID")
                                    {

                                        unit.EmployeeID = Int32.Parse(childNode.InnerText);
                                     }
                                    if (childNode.Name == "tlp:EmployeeFirstName")
                                    {
                                        unit.ProjectName = childNode.InnerText;
                                    }
                                    if (childNode.Name == "tlp:EmployeeLastName")
                                    {
                                        unit.ProjectName = childNode.InnerText;
                                    }

                                    if (childNode.Name == "tlp:AllocationID")
                                    {
                                        unit.ProjectName = childNode.InnerText;
                                    }

                                    if (childNode.Name == "tlp:TaskName")
                                    {
                                        unit.ProjectName = childNode.InnerText;
                                    }

                                }



                            output.AppendLine($"{unit.EmployeeID},{unit.EmployeeFirstName},{unit.EmployeeLastName},{unit.AllocationID},{unit.TaskName}");

                            }

                            Console.WriteLine(output.AppendLine($"{unit.EmployeeID},{unit.EmployeeFirstName},{unit.EmployeeLastName},{unit.AllocationID},{unit.TaskName}"));

                        }
                    }
                }

                else
                {
                    if (Logger.IsWarnEnabled)
                    {
                        Logger.Warn("Failed to authenticate to reporting API");
                    }
                }
            }
        }
    }
}

My OutPut file looks like this

我的OutPut文件看起来像这样

    387,,,-1,

387,,,-1,
388,,,-1,

387,,,-1,
388,,,-1,
388,,,-1,

387,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,

387,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,

387,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,

387,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,
410,,,-1,

387,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,
388,,,-1,
410,,,-1,
447,,,-1,

2 个解决方案

#1


0  

Append childNode.InnerText to the StringBuilder in each iteration:

在每次迭代中将childNode.InnerText附加到StringBuilder:

var workUnit = customersRaw.SelectNodes("tlp:WorkUnit", namespaceManager);
if (workUnit != null)
{
    var output = new StringBuilder();
    foreach (XmlNode customer in workUnit)
    {
        //var unit = new WorkUnit();
        var childNodes = customer.SelectNodes("./*");
        if (childNodes != null)
        {
            for (int i = 0; i<childNodes.Count; ++i)
            {
                XmlNode childNode = childNodes[i];
                /*if (childNode.Name == "tlp:EmployeeID")
                {
                    unit.EmployeeID = Int32.Parse(childNode.InnerText);
                }
                if (childNode.Name == "tlp:EmployeeFirstName")
                {
                    unit.ProjectName = childNode.InnerText;
                }
                if (childNode.Name == "tlp:EmployeeLastName")
                {
                    unit.ProjectName = childNode.InnerText;
                }

                if (childNode.Name == "tlp:AllocationID")
                {
                    unit.ProjectName = childNode.InnerText;
                }

                if (childNode.Name == "tlp:TaskName")
                {
                    unit.ProjectName = childNode.InnerText;
                }*/
                output.Append(childNode.InnerText);
                if(i<childNodes.Count - 1)
                    output.Append(",");
            }
            output.Append(Environment.NewLine);
        }
    }
}

#2


-2  

Try xml linq :

试试xml linq:

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

namespace ConsoleApplication1
{
    class Program
    {
        const string XML_FILENAME = @"c:\temp\test.xml";
        const string CSV_FILENAME = @"c:\temp\test.csv";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(XML_FILENAME);
            StreamWriter writer = new StreamWriter(CSV_FILENAME);

            XElement firstWorkUnit = doc.Descendants().Where(x => x.Name.LocalName == "WorkUnit").FirstOrDefault();
            XNamespace ns = firstWorkUnit.GetNamespaceOfPrefix("tlp");


            List<XElement> workUnits = doc.Descendants(ns + "WorkUnit").ToList();
            foreach (XElement workUnit in workUnits)
            {
                string outputline = string.Join(",", new string[] {
                    (string)workUnit.Element(ns + "EmployeeID"),
                    (string)workUnit.Element(ns + "AllocationID"),
                    (string)workUnit.Element(ns + "TaskID"),
                    (string)workUnit.Element(ns + "ProjectID"),
                    (string)workUnit.Element(ns + "ProjectName"),
                    (string)workUnit.Element(ns + "CustomerId"),
                    (string)workUnit.Element(ns + "CustomerName"),
                    (string)workUnit.Element(ns + "IsBillable"),
                    (string)workUnit.Element(ns + "ApprovedStatus"),
                    (string)workUnit.Element(ns + "LastModifiedBy")
                });

                writer.WriteLine(outputline);
            }

            writer.Flush();
            writer.Close();
        }
    }
}

#1


0  

Append childNode.InnerText to the StringBuilder in each iteration:

在每次迭代中将childNode.InnerText附加到StringBuilder:

var workUnit = customersRaw.SelectNodes("tlp:WorkUnit", namespaceManager);
if (workUnit != null)
{
    var output = new StringBuilder();
    foreach (XmlNode customer in workUnit)
    {
        //var unit = new WorkUnit();
        var childNodes = customer.SelectNodes("./*");
        if (childNodes != null)
        {
            for (int i = 0; i<childNodes.Count; ++i)
            {
                XmlNode childNode = childNodes[i];
                /*if (childNode.Name == "tlp:EmployeeID")
                {
                    unit.EmployeeID = Int32.Parse(childNode.InnerText);
                }
                if (childNode.Name == "tlp:EmployeeFirstName")
                {
                    unit.ProjectName = childNode.InnerText;
                }
                if (childNode.Name == "tlp:EmployeeLastName")
                {
                    unit.ProjectName = childNode.InnerText;
                }

                if (childNode.Name == "tlp:AllocationID")
                {
                    unit.ProjectName = childNode.InnerText;
                }

                if (childNode.Name == "tlp:TaskName")
                {
                    unit.ProjectName = childNode.InnerText;
                }*/
                output.Append(childNode.InnerText);
                if(i<childNodes.Count - 1)
                    output.Append(",");
            }
            output.Append(Environment.NewLine);
        }
    }
}

#2


-2  

Try xml linq :

试试xml linq:

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

namespace ConsoleApplication1
{
    class Program
    {
        const string XML_FILENAME = @"c:\temp\test.xml";
        const string CSV_FILENAME = @"c:\temp\test.csv";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(XML_FILENAME);
            StreamWriter writer = new StreamWriter(CSV_FILENAME);

            XElement firstWorkUnit = doc.Descendants().Where(x => x.Name.LocalName == "WorkUnit").FirstOrDefault();
            XNamespace ns = firstWorkUnit.GetNamespaceOfPrefix("tlp");


            List<XElement> workUnits = doc.Descendants(ns + "WorkUnit").ToList();
            foreach (XElement workUnit in workUnits)
            {
                string outputline = string.Join(",", new string[] {
                    (string)workUnit.Element(ns + "EmployeeID"),
                    (string)workUnit.Element(ns + "AllocationID"),
                    (string)workUnit.Element(ns + "TaskID"),
                    (string)workUnit.Element(ns + "ProjectID"),
                    (string)workUnit.Element(ns + "ProjectName"),
                    (string)workUnit.Element(ns + "CustomerId"),
                    (string)workUnit.Element(ns + "CustomerName"),
                    (string)workUnit.Element(ns + "IsBillable"),
                    (string)workUnit.Element(ns + "ApprovedStatus"),
                    (string)workUnit.Element(ns + "LastModifiedBy")
                });

                writer.WriteLine(outputline);
            }

            writer.Flush();
            writer.Close();
        }
    }
}