【发布时间】:2014-06-07 22:53:23
【问题描述】:
我正在尝试使用 XSLT 将 XML 文件转换为 CSV。有用。我能够使用 XSLT 转换 XML 并获得我想要的输出。
我现在面临的挑战是我在一个位置有许多 XML 文件。我想从所有 XML 中获取所有数据并将它们放入单个 CSV 文件中。我有一个 for 循环,它遍历文件夹并获取 XML 文件,然后将其导出为 CSV。但是,每次它转换新的 XML 时,它都会覆盖当前 CSV 文件中的数据。所以最终结果是我在 CSV 文件中只得到一行而不是 500 行(如果有 500 个 xml 文件)。
这是 C# 代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.IO;
using System.Diagnostics;
namespace XSL
{
class Program
{
public static void Main(string[] args)
{
try
{
//declaring xmlFile
string xmlfile ;
//Loading the XSLT template
String xsltfile = "C:\\Win\\XMLReader\\XSL\\csv.xsl";
//get folder location
string d = DateTime.Now.ToString("yyyyMMdd");
//Console.WriteLine(d.ToString());
//first part of the location path
String firstPath = @"\\tripx-exportm\\output\\Skill 53115;1_";
//full path
string fullPath = firstPath + d.ToString() + "_000000" + @"\\IDX";
//Get files from a folder
string[] filePath = Directory.GetFiles(fullPath, "*.xml");
//get each file in the folder
foreach (string file in filePath)
{
Console.WriteLine(file);
xmlfile = file;
Transform(xmlfile, xsltfile);
}
//Get the count of XML files in the current folder
DirectoryInfo dir = new DirectoryInfo(fullPath);
int count = dir.GetFiles().Length;
Console.WriteLine("Count of XML files: " + count);
//Transform(xmlfile, xsltfile);
Console.WriteLine("press any key");
Console.ReadKey();
}
catch(Exception e){
Console.WriteLine(e.ToString());
}
}
public static void Transform(string xml, string xslt)
{
try
{
//load the xml doc
XPathDocument myDoc = new XPathDocument(xml);
XslCompiledTransform myXL = new XslCompiledTransform();
//load the xslt doc
myXL.Load(xslt);
//create the output
XmlTextWriter myWriter = new XmlTextWriter("result.csv", null);
myXL.Transform(myDoc, null, myWriter);
myWriter.Close();
}
catch (Exception e)
{
Console.WriteLine("exception : {0}", e.ToString());
};
}
}
}
关于如何将多个 XML 中的数据放入单个 CSV 的任何建议?
谢谢
【问题讨论】:
-
我说这个问题真的是“如何在使用
XmlTextWriter时附加到文件吗?” -
要读取多个文档,请查看
document()函数。您必须想出一些机制(参数、控制文件等)来告诉样式表您要阅读哪些文档。