【问题标题】:XSLT select node without loosing attributesXSLT 选择节点而不丢失属性
【发布时间】:2020-12-03 00:44:44
【问题描述】:

我正在尝试对 xml 标签进行 xslt 转换,输出按预期进行,但所有属性值都被修剪掉了。我希望所有属性都需要应用,但需要像属性名称一样修改特定属性。

请看下面的例子。

<section>
  <line number='1' style='none' bold='true' size='10pt'>Line 1</line>
  <line number='2' bold='true' >Line 2</line>
  <line number='3' style='none' bold='true' size='10pt' color='red'>Line 3</line>
</section>

这个我想改成

<div>
      <p num='1' style='none' bold='true' size='10pt'>Line 1</p>
      <p num='2' b='true' >Line 2</p>
      <p num='3' style='none' bold='true' size='10pt' color='red'>Line 3</p>
</div>

这是我到目前为止写的例子。但这很复杂,因为我不能假设应用了哪个属性,所以我不想明确给出属性的名称。

<xsl:template match="section"><div use-attribute-sets="default"><xsl:apply-templates select="node()"/></div></xsl:template>

<xsl:template match="p"><p use-attribute-sets="default"><xsl:apply-templates select="node()"/></p></xsl:template>

        <xsl:attribute-set name="default">
            <xsl:attribute name="number"><xsl:value-of select="@num"/></xsl:attribute>
            <xsl:attribute name="style"><xsl:value-of select="@style"/></xsl:attribute>
            <xsl:attribute name="b"><xsl:value-of select="@bold"/></xsl:attribute>
            <xsl:attribute name="size"><xsl:value-of select="@size"/></xsl:attribute>
            <xsl:attribute name="color"><xsl:value-of select="@color"/></xsl:attribute>
        </xsl:attribute-set>

【问题讨论】:

  • 您可以在每个应用的节点上应用模板选择=“@*”。然后,您可以使用 和其他特定匹配模板为特定属性创建 match="@*" 模板,这些模板确实会更改,例如 match="@bold"。但我不确定您是否正在搜索此内容,因为我没有完全理解您的要求。
  • 让我们解决第一个问题。我希望按原样应用所有属性,因此我无需明确提及属性。就像一个标签有 3 个属性,另一个标签有 5 个属性。我不知道这些属性的名称是什么,但所有属性都需要复制。

标签: java xml xslt


【解决方案1】:

如果您想在默认情况下复制所有现有属性,但有一些例外,您可以通过以下代码实现:

<xsl:template match="*"> <!-- This matches all nodes. Note that specific templates have higher priority and will hit earlier (You can probably use your match="p" or "line") -->
    <xsl:apply-templates select="@*"/> <!-- Default value if no select is given is '*' so no attributes would be hit -->
</xsl:template>

<xsl:template match="@*"> <!-- Match all the attributes so you can copy them -->
    <xsl:copy/>
</xsl:template>

<xsl:template match="@bold"> <!-- Note that this will hit instead of @* because its more specific as described above -->
    <xsl:attribute name="b" select="."/>
</xsl:template>
<!-- Here you can specify more of such attribute matches if needed -->

【讨论】:

  • 哇,现在它按预期工作了,我在您给出的示例中使用了以下解决方法。
  • 这一行出现错误。.它说“非法属性'select'”
  • 这对我有用。
  • 我没有在编辑器中测试它,所以可能有一些语法错误。但我很高兴你找到了解决方案。 :)
猜你喜欢
  • 2022-12-19
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2015-05-14
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多