2012年12月2日日曜日

XSLTを使ってSPARQL Query Results XML FormatをCSV/TSV形式にする

SPARQL Query Results XML FormatにあるXSLTサンプルresult-to-html.xslを少し書き換えてCSV/TSVを出力するようにしてみた.

<?xml version="1.0" encoding="UTF-8"?>  
<xsl:stylesheet exclude-result-prefixes="res xsl" version="1.0" xmlns:res="http://www.w3.org/2005/sparql-results#" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">
  <xsl:output encoding="UTF-8" method="text">
    <xsl:template name="boolean-result">
      <xsl:value-of select="res:boolean">
  </xsl:value-of></xsl:template>
  <xsl:template name="vb-result">
   <xsl:for-each select="res:head/res:variable">
     <xsl:value-of select="@name">
     <xsl:text>,</xsl:text>
   </xsl:value-of></xsl:for-each>
 <xsl:for-each select="res:results/res:result">
<xsl:text>
</xsl:text>
     <xsl:apply-templates select=".">
  </xsl:apply-templates></xsl:for-each>
  </xsl:template>
  <xsl:template match="res:result">
    <xsl:variable name="current" select=".">
    <xsl:for-each select="//res:head/res:variable">
      <xsl:variable name="name" select="@name">
 <xsl:choose>
   <xsl:when test="$current/res:binding[@name=$name]">
     <xsl:apply-templates select="$current/res:binding[@name=$name]">
   </xsl:apply-templates></xsl:when>
   <xsl:otherwise>
   </xsl:otherwise>
 </xsl:choose>
 <xsl:text>,</xsl:text>
    </xsl:variable></xsl:for-each>
  </xsl:variable></xsl:template>
  <xsl:template match="res:bnode">
    <xsl:value-of select="text()">
  </xsl:value-of></xsl:template>
  <xsl:template match="res:uri">
    <xsl:variable name="uri" select="text()">
<xsl:value-of select="$uri">
 </xsl:value-of></xsl:variable></xsl:template>
  <xsl:template match="res:literal">
    <xsl:choose>
<!--
      <xsl:when test="@datatype">
 <xsl:value-of select="text()"/> (datatype <xsl:value-of select="@datatype"/> )
      </xsl:when>
      <xsl:when test="@xml:lang">
 <xsl:value-of select="text()"/> @ <xsl:value-of select="@xml:lang"/>
      </xsl:when>
      <xsl:when test="string-length(text()) != 0">
 <xsl:value-of select="text()"/>
      </xsl:when>
      <xsl:when test="string-length(text()) = 0">
      <xsl:text></xsl:text>
      </xsl:when>
-->
      <xsl:when test="string-length(text()) != 0">
 <xsl:value-of select="text()">
      </xsl:value-of></xsl:when>
    </xsl:choose>
  </xsl:template>
  <xsl:template match="res:sparql">
     <xsl:choose>
   <xsl:when test="res:boolean">
     <xsl:call-template name="boolean-result">
   </xsl:call-template></xsl:when>
   <xsl:when test="res:results">
     <xsl:call-template name="vb-result">
   </xsl:call-template></xsl:when>
 </xsl:choose>
  </xsl:template>
</xsl:output>
</xsl:stylesheet>
TSVを出力する場合は「,」とある箇所をタブに書き換えればよい.


0 件のコメント:

コメントを投稿