Created
February 17, 2020 19:28
-
-
Save robvitaro/0aad995eac3041e2f4ebd505d6efa256 to your computer and use it in GitHub Desktop.
Flatten an XML file to "full-xpath,value" csv file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> | |
<xsl:output omit-xml-declaration="yes" indent="yes"/> | |
<xsl:strip-space elements="*"/> | |
<xsl:template match="*[@* or not(*)] "> | |
<xsl:if test="not(*)"> | |
<xsl:apply-templates select="ancestor-or-self::*" mode="path"/> | |
<xsl:value-of select="concat(',',.)"/> | |
<xsl:text>
</xsl:text> | |
</xsl:if> | |
<xsl:apply-templates select="@*|*"/> | |
</xsl:template> | |
<xsl:template match="*" mode="path"> | |
<xsl:value-of select="concat('/',name())"/> | |
<xsl:variable name="vnumPrecSiblings" select= | |
"count(preceding-sibling::*[name()=name(current())])"/> | |
<xsl:if test="$vnumPrecSiblings"> | |
<xsl:value-of select="concat('[', $vnumPrecSiblings +1, ']')"/> | |
</xsl:if> | |
</xsl:template> | |
<xsl:template match="@*"> | |
<xsl:apply-templates select="../ancestor-or-self::*" mode="path"/> | |
<xsl:value-of select="concat('[@',name(),'],',.)"/> | |
<xsl:text>
</xsl:text> | |
</xsl:template> | |
</xsl:stylesheet> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'nokogiri' | |
document = Nokogiri::XML(File.read('input.xml')) | |
template = Nokogiri::XSLT(File.read('transformer.xslt')) | |
transformed_document = template.transform(document) | |
File.open('output.csv', 'w').write(transformed_document) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
just have a file
input.xml
in the same directory these 2 files are in and run:ruby xslt.rb
output.csv will spit out