XSLT 1.0,XML到CSV:如何从属性和子节点检索头 [英] XSLT 1.0, XML to CSV: how to retrieve headers from attributes and child nodes
问题描述
考虑以下XML输入:
<LIST>
<DIRECTORIES>
<DIRECTORY ID="000001">
<NAME>folder</NAME>
<LOCATION>C:\here</LOCATION>
</DIRECTORY>
<DIRECTORY ID="000002">
<COLOR>blue</COLOR>
<LOCATION>C:\here</LOCATION>
<DATE>01-25-2015</DATE>
</DIRECTORY>
<DIRECTORIES>
<FILES>
<FILE ID="000001">
<NAME>file</NAME>
<TYPE>rt</TYPE>
<SERVICE>inf</SERVICE>
</FILE>
<FILE ID="000002">
<NAME>f</NAME>
</FILE>
</FILES>
<LIST>
我想检索DIRECTORIES的内容,每个不同的DIRECTORY的子节点和属性。在此示例中,所需的输出为:
I'd like to retrieve the content of DIRECTORIES, with one header per distinct DIRECTORY's child node and attributes. In this example, the desired output would be:
ID, NAME, LOCATION, COLOR, DATE
000001, folder, C:\here,,
000002,,C:\here,blue,01-25-2015
有很多关于XML到CSV转换的问题,所以我试图调整在另一个提供的解决方案,没有成功。这是我的XSLT:
There are a lot of questions regarding XML to CSV transformations, so I tried to tweak a solution offered in another one, without success. Here's my XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:variable name="delimiter" select="','"/>
<xsl:key name="directoryFields" match="/LIST/DIRECTORIES/DIRECTORY/*" use="local-name()"/>
<xsl:variable name="dirFields"
select="/LIST/DIRECTORIES/DIRECTORY/*[generate-id()=generate-id(key('directoryFields', local-name())[1])]" />
<xsl:template match="/">
<xsl:for-each select="$dirFields">
<xsl:value-of select="local-name()" />
<xsl:if test="position() < last()">
<xsl:value-of select="$delimiter" />
</xsl:if>
</xsl:for-each>
<xsl:text> </xsl:text>
<xsl:apply-templates select="*/*" />
</xsl:template>
<xsl:template match="*">
<xsl:variable name="this" select="." />
<xsl:for-each select="$dirFields">
<xsl:value-of select="$this/*[local-name() = local-name(current())]" />
<xsl:if test="position() < last()">
<xsl:value-of select="$delimiter" />
</xsl:if>
</xsl:for-each>
<xsl:text> </xsl:text>
</xsl:template>
</xsl:stylesheet>
推荐答案
好:
<xsl:apply-templates select="*/*" />
必须为:
<xsl:apply-templates select="LIST/DIRECTORIES/DIRECTORY" />
您选择 LIST / DIRECTORIES
。并且不能使用 * / * / *
,因为它也选择了FILE节点。
What you have selects LIST/DIRECTORIES
. And you cannot use */*/*
because that selects the FILE nodes, too.
删除此行:
<xsl:value-of select="/LIST/DIRECTORIES/DIRECTORY"/>
添加
added
为了包含ID,您必须添加:
In order to include the ID, you must add this:
<xsl:value-of select="concat(@ID, $delimiter)" />
到模板处理DIRECTORY,然后再继续处理字段。
to the template processing DIRECTORY, before moving on to process the fields.
这篇关于XSLT 1.0,XML到CSV:如何从属性和子节点检索头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!