如何通过xslt从嵌套xml中的父标记中提取childelement?

时间:2019-01-25 15:34:23

标签: xml xslt

如何通过xslt从嵌套xml中的父标记中提取子元素 它有两个名称相同的标签,我想将其分为两个不同的标签。

我的xml是这样的:

<div>
    <title> Additional info </title>
    <h2> heading </h2>
    <div>
    <title> click info </title>
    </div>
</div>

输出应为:

<section>
    <title> Additional info </title>
    <h2> heading </h2>
</section>
<section>
    <title> click info </title>
</section>

我的xslt代码是:

    <xsl:template match="content/body//div">
    <xsl:choose>
        <xsl:when test="div">
        <xsl:apply-templates/>
        </xsl:when>
            <xsl:otherwise>
            <section>
                <xsl:apply-templates/>
            </section>
            </xsl:otherwise>
            </xsl:choose>
        </xsl:template>


    <xsl:template match="content/body/section/div">
        <xsl:apply-templates select ="./node()"/>
    </xsl:template>

使用这个我得到输出:

    <title> Additional info </title>
            <h2> heading </h2>
        <section>
            <title> click info </title>
        </section>

2 个答案:

答案 0 :(得分:0)

这是所有直接子元素名称的更新。

<div>
    <title> Additional info </title>
    <h2> heading </h2>
    <div>
    <title> click info </title>
    </div>
    <div>
        <em>Release</em>
    </div>
</div>

和xsl

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

<xsl:variable name='list' select='//div'/>

<xsl:template match='/'>
    <div>
        <xsl:for-each select='$list'>
            <xsl:element name='select'>
                <xsl:copy-of select='*[not(name(.)="div")]'/>
            </xsl:element>
        </xsl:for-each>
    </div>
</xsl:template>
</xsl:stylesheet>

输出

<div>
  <select>
    <title>Additional info</title>

    <h2>heading</h2>
  </select>

  <select>
    <title>click info</title>
  </select>

  <select>
    <em>Release</em>
  </select>
</div>

答案 1 :(得分:0)

感谢您的帮助!! 现在使用以下代码工作

    <xsl:for-each select='$list'>
        <xsl:element name='section'>
            <xsl:apply-templates select='*[not(name(.)="div")]'/>

        </xsl:element>
    </xsl:for-each>