【问题标题】:XSLT Move child elements into new parent nodeXSLT 将子元素移动到新的父节点
【发布时间】:2017-08-04 20:39:19
【问题描述】:

我对 XSLT 非常陌生,正在尝试转换此 XML:

<Company>
   <Employee>
       <name>Jane</name>
       <id>200</id>
       <title>Dir</title>
       <name>Joe</name>
       <id>100</id>
       <title>Mgr</title>
       <name>Sue</name>
       <id>300</id>
       <title>Analyst</title>
   </Employee>
 </Company>

到这个预期的输出:

<Company>
   <Employee>
       <name>Jane</name>
       <id>200</id>
       <title>Dir</title>
   </Employee>
   <Employee>
       <name>Joe</name>
       <id>100</id>
       <title>Mgr</title>
   </Employee>
   <Employee>
       <name>Sue</name>
       <id>300</id>
       <title>Analyst</title>
   </Employee>
</Company>

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 可以假设一个统一的结构 {name; ID;标题}?

标签: xml 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="/Company">
    <xsl:copy>
        <xsl:for-each select="Employee/name">
            <Employee>
                <xsl:copy-of select=". | following-sibling::id[1] | following-sibling::title[1]"/>
            </Employee>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

或更通用的:

<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:param name="group-size" select="3" />

<xsl:template match="/Company">
    <xsl:copy>
        <xsl:for-each select="Employee/*[position() mod $group-size = 1]">
            <Employee>
                <xsl:copy-of select=". | following-sibling::*[position() &lt; $group-size]"/>
            </Employee>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

【讨论】:

  • 对不起,我刚才有机会回复。在原始 XML 中,它们总是以三个一组的形式出现。我在样式表中尝试了你的建议,它奏效了。谢谢!
猜你喜欢
  • 2021-02-02
  • 2021-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多