我正在努力绕过xslt …试图转换下面的xml: employees employee employeeNumber1234/employeeNumber startdate01/02/2003/startdate activeFlagtrue/activeFlag firstnameErik/firstname address addressline1123 Main/addressline1 zip07016
<employees> <employee> <employeeNumber>1234</employeeNumber> <startdate>01/02/2003</startdate> <activeFlag>true</activeFlag> <firstname>Erik</firstname> <address> <addressline1>123 Main</addressline1> <zip>07016</zip> <state>New Jersey</state> <city>My City</city> </address> </employee> </employees>
进入这个(即取出activeFlag标签值并将其放入employee标签的属性中).
<employees> <employee active="true"> <employeeNumber>1234</employeeNumber> <startdate>01/02/2003</startdate> <firstname>Erik</firstname> <address> <addressline1>123 Main</addressline1> <zip>07016</zip> <state>New Jersey</state> <city>My City</city> </address> </employee> </employees>
我尝试了以下XSLT,但它什么也没做:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="employees/employee"> <employee active="{activeFlag}"/> </xsl:template> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
有任何想法吗?
这个简短而简单(没有明确的条件指令)转换:<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="employee"> <employee active="{activeFlag}"> <xsl:apply-templates select="node()|@*"/> </employee> </xsl:template> <xsl:template match="activeFlag"/> </xsl:stylesheet>
当应用于提供的XML文档时:
<employees> <employee> <employeeNumber>1234</employeeNumber> <startdate>01/02/2003</startdate> <activeFlag>true</activeFlag> <firstname>Erik</firstname> <address> <addressline1>123 Main</addressline1> <zip>07016</zip> <state>New Jersey</state> <city>My City</city> </address> </employee> </employees>
产生想要的,正确的结果:
<employees> <employee active="true"> <employeeNumber>1234</employeeNumber> <startdate>01/02/2003</startdate> <firstname>Erik</firstname> <address> <addressline1>123 Main</addressline1> <zip>07016</zip> <state>New Jersey</state> <city>My City</city> </address> </employee> </employees>
说明:覆盖identity rule,使用AVT.
如果你想正确处理没有activeFlag子元素的情况,它会变得稍微复杂一些:
<xsl:template match="employee"> <employee active= "{concat(activeFlag, substring('false', 1 div not(activeFlag)) ) }"> <xsl:apply-templates select="node()|@*"/> </employee> </xsl:template>