【发布时间】:2016-11-18 15:46:04
【问题描述】:
我了解 XPath 语法的工作原理,并且可以编写 Xpath 命令以从 XML 文件中提取某些信息。
我想将我的 XPath 命令转换为 XSLT 脚本,以便其他人可以通过 XML 文件运行脚本以获得相同的输出。
例如
我有一个 XML 文件,比如说,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<library>
<section id="109196796">
<master_information>
<shelf_identifier>
<identifier type="CodeX" type_id="2">LB1500605917</identifier>
<identifier type="Common Code" type_id="15">150060591</identifier>
</shelf_identifier>
<shelf_master>
<section_type>1</section_type>
<book_type>3</book_type>
</shelf_master>
</master_information>
</section>
<section id="109196798">
<master_information>
<shelf_identifier>
<identifier type="CodeX" type_id="2">LB0777775917</identifier>
<identifier type="Common Code" type_id="15">077777591</identifier>
</shelf_identifier>
<shelf_master>
<section_type>1</section_type>
<book_type>3</book_type>
</shelf_master>
</master_information>
</section>
<section id="109196800">
<master_information>
<shelf_identifier>
<identifier type="CodeX" type_id="2">LB2589165917</identifier>
<identifier type="Common Code" type_id="15">258916591</identifier>
</shelf_identifier>
<shelf_master>
<section_type>1</section_type>
<book_type>3</book_type>
</shelf_master>
</master_information>
</section>
</library>
如果我运行下面的 XPath 命令,
//identifier[@type='CodeX']
我得到了输出:
LB1500605917
LB0777775917
LB2589165917
..这是预期的。现在,我尝试将 XPath 命令转换为 XSL 语法,如下所示:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:variable name="return">
<xsl:text>
</xsl:text> <!-- defined a line break -->
</xsl:variable>
<xsl:template match="//library"></xsl:template>
<xsl:template match="//section/master_information/shelf_identifier/identifier">
<xsl:value-of select="@type='CodeX'"/>
<xsl:value-of select="$return"/> <!-- this basically puts a line break -->
</xsl:template>
</xsl:stylesheet>
XSL 似乎是正确的。但是,不会生成任何输出。
我是 XSL/XSLT 的新手。我究竟做错了什么?
【问题讨论】:
-
您是否尝试过仅使用一个模板或在 value-of select 上指定 xpath??
-
感谢您的回复。我尝试删除库模板并将第二个模板更改为“//标识符”我得到以下输出:true false 13true false 13true false 13 这没有意义,因为它们甚至不存在于文件中。
-
@Pernambuco - 如果您在 xsl:value-of 选择中使用相同的 XPath (
//identifier[@type='CodeX']),并且您使用的是 XSLT 1.0,那么您只会获得第一个值。跨度>