如何编写 XSLT 将 XML 转换为 CSV? [英] How do I write an XSLT to transform XML to CSV?

查看:19
本文介绍了如何编写 XSLT 将 XML 转换为 CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 XSLT,它将我拥有的 XML 文档转换为 CSV 文件.这是 XML 的示例:

I'm trying to write an XSLT that will transform an XML document that I have to a CSV file. Here's a sample of the XML:

<?xml version="1.0" encoding="utf-8"?>
<Import>
    <Users>
        <User ID="user_1" EmailAddress="johndoe@somewhere.com">
            <Contact FirstName="John" LastName="Doe" />
            <Address Street1="808 Elm St" City="Anywhere" State="NY" />
        </User>

        <User ID="user_2" EmailAddress="janenoone@somewhere.com">
            <Contact FirstName="Jane" LastName="Noone" />
            <Address Street1="123 Some Rd" City="Anywhere" State="NY" />
        </User>     
    </Users>
</Import>

我想要的是一个像这样输出的 XSLT:

What I want is an XSLT that will output like so:

John,Doe,808 Elm St,Anywhere,NY
Jane,Noone,123 Some Rd,Anywhere,NY

我认为我有正确的 C# 代码来启动转换,但以防万一,这里也有该代码:

I think I have the C# code correct to initiate the transform, but just in case I don't, here's that code as well:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Configuration;

namespace UserTransform
{
    class Program
    {
        static void Main(string[] args)
        {
            string oldXML = ConfigurationSettings.AppSettings["XMLToBeTransformed"];
            string xsltLocation = ConfigurationSettings.AppSettings["XSLTfile"];
            string newCSV = ConfigurationSettings.AppSettings["NewCSVLocation"];

            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(xsltLocation);
            transform.Transform(oldXML, newCSV);
        }
    }
}

推荐答案

创建一个匹配所有用户的模板,然后按照你想要的顺序拉出你需要的信息:

Create a template that matches all users, then pull out the information you need in the order you want:

<xsl:template match="//User">
  <xsl:value-of select="Contact/@FirstName"/>,
  <xsl:value-of select="Contact/@LastName"/>,
  <!--etc-->
</xsl:template>

显然,您需要确保按照您希望的方式处理空格,并在正确的位置使用换行符.我将把它作为练习留给读者.

Obviously you'll need to make sure whitespace is handled the way you want it to be, with newlines in the right places. I'll leave this as an exercise to the reader.

这篇关于如何编写 XSLT 将 XML 转换为 CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆