【问题标题】:subsequent element as attribute in xml using xslt使用 xslt 在 xml 中作为属性的后续元素
【发布时间】:2017-11-21 18:30:31
【问题描述】:

如果后续元素使用 XSLT 包含前面的元素名称,则需要帮助将后续元素作为前面元素的属性。

对于下面的示例,emp_id> 包含前面的元素名称,因此需要将此元素作为属性转换为元素。你可以帮忙吗?我尝试在 xslt 中使用后续函数但不工作。提前致谢。

示例 XML:

<root>
    <emp>test</emp>
    <emp_id>1234</emp_id>
    <college>something</college>
</root>

预期结果:

<root>
    <emp id="1234">test</emp>
    <college>something</college>
</root>

【问题讨论】:

  • 是否可以假设名称中包含_ 的每个元素都有一个“父”元素,其属性应该成为?
  • 是的,我们可以假设。

标签: java xml xslt xslt-1.0


【解决方案1】:

在给定的示例中,您可以这样做:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:apply-templates select="following-sibling::*[starts-with(name(), name(current()))]" mode="attr"/>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="attr">
    <xsl:attribute name="{substring-after(name(), '_')}">
        <xsl:value-of select="." />
    </xsl:attribute>
</xsl:template>

<xsl:template match="*[preceding-sibling::*[name()=substring-before(name(current()), '_')]]"/>

</xsl:stylesheet>

达到预期的效果。


可能有更优雅的方式,但我们需要更多的规则,而不只是一个例子。


补充:

假设名称包含_ 的每个元素都有一个“父”元素,其属性应该成为,您可以首先将模板应用于“父”元素(即名称不包含'_ ')。

然后使用key来收集需要转化为属性的“子”元素。

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="atr" match="*" use="substring-before(name(), '_')" />

<xsl:template match="/root">
    <xsl:copy>
        <xsl:apply-templates select="*[not(contains(name(), '_'))]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:for-each select="key('atr', name())">
            <xsl:attribute name="{substring-after(name(), '_')}">
                <xsl:value-of select="." />
            </xsl:attribute>
        </xsl:for-each>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

【讨论】:

  • 是否可以使用 _ 检查前面的元素名称,然后将元素转换为属性。例如: 我们需要查找 emp_,其中 emp 是前面的元素名称,而 _ 是常量。
猜你喜欢
  • 2010-10-13
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多