xslt得到紧接着的兄弟姐妹

时间:2017-04-05 08:46:10

标签: html xslt xslt-1.0 xslt-2.0 marc

我有以下内容:

 <root>
  <html>
   <table
    <tr> 
     <td width="1%" height="20"></td>
     <td width="18%">Book Location </td>
     <td width="81%">Technology (Applied sciences) Circulation</td>
    </tr>

我尝试在xslt下面获取直接节点内容,其中td的节点内容是&#34;预订位置&#34;:

<?xml version="1.0" encoding="utf-8"?>
 <xsl:stylesheet version="1.0"
 xmlns:marc="http://www.loc.gov/MARC21/slim"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text" indent="yes" />

 <xsl:template match="root">
  <xsl:for-each select="html">
  <xsl:text>START HERE</xsl:text>
  <xsl:text>&#13;&#10;</xsl:text>
  <xsl:text>=LDR  00000nam  2200000Ia 4500</xsl:text>
  <xsl:text>&#13;&#10;</xsl:text>

  <xsl:if test="//*[text()='Book Location ']">
   <xsl:text>=952  \\$cLocation: </xsl:text>
   <xsl:value-of select="following-sibling" />
  </xsl:if> 

  </xsl:for-each>

  </xsl:template>
 </xsl:stylesheet>

我不确定该部分应该放什么:       或者,如果有更好的方法吗? 提前致谢,祝你有愉快的一天!

2 个答案:

答案 0 :(得分:1)

您可以使用:

<xsl:value-of select="//*[text()='Book Location ']/following-sibling::*[1]" />

而不是

<xsl:value-of select="following-sibling" />

答案 1 :(得分:1)

您的模板表明您像一个程序语言程序员一样思考。 XSLT可以用这个成语或多或少地编写,但它不是XSLT的自然习语。以这种方式编写的代码往往比更自然的代码更长更麻烦。特别是,虽然它们有很好的用途,但for-each元素通常带有一点代码味道。

这对我来说似乎更自然,而且似乎有效(但我必须测试输入的修改版本,因为你提供的内容不是有效的XML):

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" indent="yes" />

  <xsl:template match="/root/html">
    <xsl:text>START HERE</xsl:text>
    <xsl:text>&#13;&#10;</xsl:text>
    <xsl:text>=LDR  00000nam  2200000Ia 4500</xsl:text>
    <xsl:text>&#13;&#10;</xsl:text>
    <xsl:apply-templates select="descendant::td[text() = 'Book Location ']" />
  </xsl:template>

  <xsl:template match="td">
   <xsl:text>=952  \\$cLocation: </xsl:text>
   <xsl:value-of select="following-sibling::*[1]" />
  </xsl:template> 

</xsl:stylesheet>

注意:

  • 更具体的匹配表达式无需原始
  • 中的for-each
  • 不是尝试将整个转换放入一个模板,而是使用单独的模板来转换单独的元素。这不仅更简洁,而且还有助于简化表达式,因为每个模板都与其自己的上下文相关联,而不是评估哪些表达式
  • 使用&#34;以下兄弟&#34;作为轴名称,而不是元素名称,您必须附加双冒号并至少添加某种节点测试
  • &#34;以下兄弟&#34; axis可以包含多个节点,因此如果您只想要紧随其后的节点,那么您需要指定(如上所述)
  • 我可能已选择直接转换包含该位置的td,而不是间接通过其标签td的模板。这对我来说似乎更干净,但我没有这样做,因为它的语义略有不同。
相关问题