1

交叉发布http://perlmonks.org/index.pl?node_id=979710

我正在尝试使用 Perl 和 Lib::XSLT 从一些 XML 创建一个文本文件,我的转换工作正常,除了 Lib::XSLT 在文件开头添加了一个不需要的 ?xml 版本标记,我怎样才能阻止它这样做?

这是我的 XSLT:

<xslt:stylesheet version="1.0" xmlns:data="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/generic" xmlns:xslt="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:message="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes"/>
<xslt:param name="sep">|</xslt:param>
<xslt:output method="text" />
<xslt:template match="message:MessageGroup">
<xslt:for-each select="data:DataSet">
<!-- get dimensions (but not time) and store in dimensions variable -->
<xslt:for-each select="data:Series">
<xslt:variable name="dimensions">
<xslt:for-each select="data:SeriesKey">
<xslt:for-each select="data:Value">
<xslt:value-of select="@value" />
<xslt:value-of select="$sep" />
</xslt:for-each>
</xslt:for-each>
</xslt:variable>
<!--get obs statuses and store in obs statuses variable-->
<xslt:variable name="obsStatuses">
<xslt:for-each select="data:Attributes">
<xslt:for-each select="data:Value">
<xslt:value-of select="@value" />
</xslt:for-each>
</xslt:for-each>
</xslt:variable>
<!--write out dimensions variable, time, observation, obsstatuses variable-->
<xslt:for-each select="data:Obs">
<xslt:value-of select="$dimensions" />
<xslt:value-of select="data:Time" />
<xslt:value-of select="$sep" />
<xslt:value-of select="data:ObsValue/@value" />
<xslt:value-of select="$sep" />
<xslt:value-of select="data:Attributes/data:Value/@value"/>
<xslt:text>
</xslt:text>
</xslt:for-each>
</xslt:for-each>
</xslt:for-each>
</xslt:template>
</xslt:stylesheet>

这是 Perl:

use Lib::XSLT;
my $parser = XML::LibXML->new();
my $xslt = XML::LibXSLT->new();
my $source = XML::LibXML->load_xml(location => "$xmlFile");
my $style_doc = $parser->parse_file(Path::Class::File->new("$xsltFile"));
my $stylesheet = $xslt->parse_stylesheet($style_doc);
open OUTPUTFILE, ">>$outputFile" or die("Unable to open $outputFile, $!");
print OUTPUTFILE $stylesheet->transform($source);
close OUTPUTFILE;
4

2 回答 2

1

存储 $stylesheet->transform() 的结果并使用 $stylesheet->output_file() 可以解决这个问题,例如:

use Lib::XSLT;
my $parser = XML::LibXML->new();
my $xslt = XML::LibXSLT->new();
my $source = XML::LibXML->load_xml(location => "$xmlFile");
my $style_doc = $parser->parse_file(Path::Class::File->new("$xsltFile"));
my $stylesheet = $xslt->parse_stylesheet($style_doc);
my $results = $stylesheet->transform($source);
$stylesheet->output_file($results, $outputFile);
于 2012-07-05T22:50:20.210 回答
0

为什么<?xml>不需要声明?它是有效的 XML,并且对解析器没有影响。

于 2012-07-03T15:41:43.850 回答