以下是用作源的 XML 文件:
<?xml version="1.0" encoding="UTF-8" ?>
<billing-log>
<log-start-date>2012-08-17T00:00:00-05:00</log-start-date>
<player-name>Player1</player-name>
<schema-version>1</schema-version>
<player-uuid>12345</player-uuid>
<log-end-date>2012-08-17T23:59:59.999-05:00</log-end-date>
<entry>
<page>Page1</page>
<path>Path1</path>
<in>2012-08-16T23:59:52.170-05:00</in>
<out>2012-08-17T00:00:00.186-05:00</out>
</entry>
<entry>
<page>Page2</page>
<path>Path2</path>
<in>2012-08-17T00:00:00.186-05:00</in>
<out>2012-08-17T00:00:08.561-05:00</out>
</entry>
</billing-log>
我正在使用的 xsl 文件是这样的:
<?xml version="1.0"?>
<xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="log-start-date"></xsl:template>
<xsl:template match="player-name"></xsl:template>
<xsl:template match="schema-version"></xsl:template>
<xsl:template match="player-uuid"></xsl:template>
<xsl:template match="log-end-date"></xsl:template>
<xsl:template match="//entry">
<xsl:text>"</xsl:text>
<xsl:value-of select="normalize-space(page)"/><xsl:text/>
<xsl:text>","</xsl:text>
<xsl:value-of select="normalize-space(path)"/><xsl:text/>
<xsl:text>","</xsl:text>
<xsl:value-of select="normalize-space(in)"/><xsl:text/>
<xsl:text>","</xsl:text>
<xsl:value-of select="normalize-space(out)"/><xsl:text/>
<xsl:text>" </xsl:text>
<xsl:text disable-output-escaping = "yes" >
</xsl:text>
</xsl:template>
</xsl:stylesheet>
我将这些输入到以下 c# 控制台应用程序中,以将其转换为 CSV 并将其写入文件。:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
namespace xml2csv
{
class Program
{
static int Main(string[] args)
{
if (args.Length != 3)
{
System.Console.WriteLine("Wrong number of aruguments");
return -1;
}
string xmlFile = args[0];
string xslFile = args[1];
string outputFile = args[2];
//Create a new XML document and load the XML file
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
//Create an XSLT object and load the XSLT file
XslCompiledTransform xslTran = new XslCompiledTransform();
xslTran.Load(xslFile);
// This is for generating the output
XmlTextWriter writer = new XmlTextWriter(outputFile, System.Text.Encoding.ASCII);
//Apply the transformation and write disk
xslTran.Transform(xmlDoc, null, writer);
//Close the writer
writer.Close();
return 1;
}
}
}
它产生的结果是:
"Page1","Path1","2012-08 16T23:59:52.170-05:00","2012-08-17T00:00:00.186-05:00"
"Page2","Path2","2012-08-17T00:00:00.186-05:00","2012-08-17T00:00:08.561-05:00"
我想要的是预先为 log-end-date 的兄弟节点值记录入口节点。所以输出看起来像这样:
"2012-08-17T23:59:59.999-05:00","Page1","Path1","2012-08 16T23:59:52.170-05:00","2012-08-17T00:00:00.186-05:00"
"2012-08-17T23:59:59.999-05:00","Page2","Path2","2012-08-17T00:00:00.186-05:00","2012-08-17T00:00:08.561-05:00"
任何帮助,将不胜感激。