【发布时间】:2016-06-09 21:18:33
【问题描述】:
我正在尝试使用 XSLT 1.0 执行简单的 xml 转换。 这是我的 xml 和 xslt 文件。
XML 文件
<?xml version="1.0"?>
<?xml-stylesheet type="xsl" href="trans.xsl"?>
<Article>
<Title>My Article</Title>
<Authors>
<Author>Mr. Foo</Author>
<Author>Mr. Bar</Author>
</Authors>
<Body>This is my article text.</Body>
</Article>
XSLT 文件
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
Article - <xsl:value-of select="/Article/Title"/>
Authors: <xsl:apply-templates select="/Article/Authors/Author"/>
</xsl:template>
<xsl:template match="Author">
- <xsl:value-of select="." />
</xsl:template>
</xsl:stylesheet>
这是我正在使用的 perl 脚本。
use strict;
use warnings;
use Getopt::Std;
use File::Path;
use File::Spec;
use File::Basename;
use Env;
use XML::LibXSLT;
use XML::LibXML;
my %opts = ();
getopts('p:f:'\%opts);
my $xsltfile = $opts{'p'};
die "XSLT file not specified" if !defined($xsltfile);
my $xmlfile = $opts{'f'};
die "XML file not specified" if !defined($xmlfile);
# XSLT Transformation code starts here
#my $xml_parser = XML::LibXML->new();
#my $source = $xml_parser->parse_file($msgcatfile);
my $source = XML::LibXML->load_xml(location => $xmlfile);
#my $xslt_parser = XML::LibXML->new();
#my $xslt_source = $xslt_parser->parse_file($xsltfile);
my $xslt_source = XML::LibXML->load_xml(location => $xsltfile);
my $xslt = XML::LibXSLT->new();
my $stylesheet;
eval { $stylesheet = $xslt->parse_stylesheet($xslt_source); };
if ($@)
{
print "$@";
die "\n!******************Error in parsing the stylesheet file : $xsltfile ************************!\n";
}
eval { my $results = $stylesheet->transform_file($source); };
if ($@)
{
print "$@";
die "\n!******************Error in transforming the input xml file : $source ************************!\n";
}
print $stylesheet->output_as_bytes($results);
0;
我不确定出了什么问题,但是在运行这个 perl 脚本时,我遇到了以下我无法解读的错误。
Bareword found where operator expected at trans.xslt line 2, near ""1.0" xmlns"
(Missing operator before xmlns?)
Bareword found where operator expected at trans.xslt line 11, near "</xsl"
(Might be a runaway multi-line // string starting on line 10)
(Missing operator before l?)
syntax error at trans.xslt line 2, near "xsl:"
Execution of trans.xslt aborted due to compilation errors.
当我在错误消息中搜索关键字时,我找不到任何类似的帖子(与 XML/XSLT 相关)。 我错过了什么明显的东西吗?
:更新:
我以
身份运行我的程序perl transform.pl -p trans.xslt -f example.xml
【问题讨论】:
-
你如何运行你的程序?看起来您尝试使用 perl 运行 xsl 文件。
-
您已经显示了两次 XSLT 文件。请出示您的 XML
-
您显示的 Perl 代码无法编译并显示消息
Global symbol "$results" requires explicit package name。其实getopts('p:f:'\%opts)这行也是非法的,不过为了方便测试我把它去掉了。请显示给你这个错误的真实代码 -
我打赌是他的代码。他只是从来没有执行过它,因为(不知何故)他正在执行 XSLT,而不是 Perl。
-
@DaveCross: 哈哈,那个让我头疼!