如何将不同的模板应用于具有相同名称的不同子节点?
我得到了一个我无法改变的xml。
为了过度简化一个例子(真正的xml比这复杂得多),我想将不同的模板应用于员工和经理,但他们的子节点都是"员工"。下面的xslt不起作用,因为有2个Employee模板。
仅供参考,我是xslts的新手,所以如果事实证明这很容易解决,我会道歉。
提前致谢!任何帮助将不胜感激。
XML
<Company>
<CompanyId>1</CompanyId>
<CompanyName>Company B</CompanyName>
<Employees>
<Employee>
<EmployeeId>1</EmployeeId>
<FirstName>Jane</FirstName>
<LastName>Doe</LastName>
</Employee>
<Employee>
<EmployeeId>2</EmployeeId>
<FirstName>James</FirstName>
<LastName>Smith</LastName>
</Employee>
</Employees>
<Managers>
<Employee>
<EmployeeId>3</EmployeeId>
<FirstName>Michael</FirstName>
<LastName>Johnson</LastName>
<DepartmentName>Sales</DepartmentName>
<NumberOfStaff>20</NumberOfStaff>
</Employee>
<Employee>
<EmployeeId>2</EmployeeId>
<FirstName>James</FirstName>
<LastName>Smith</LastName>
<DepartmentName>IT</DepartmentName>
<NumberOfStaff>50</NumberOfStaff>
</Employee>
</Managers>
</Company>
XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ms="urn:schemas-microsoft-com:xslt"
xmlns:dt="urn:schemas-microsoft-com:datatypes">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="/Company"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Company">
COMPANY INFO<br />
Company Id: <xsl:value-of select="CompanyId" /><br />
Company Name: <xsl:value-of select="CompanyName" /><br />
<br />
EMPLOYEES<br />
<xsl:apply-templates select="/Company/Employees/Employee"/>
<br />
MANAGERS<br />
<xsl:apply-templates select="/Company/Managers/Employee"/>
<br />
</xsl:template>
<xsl:template match="Employee">
<br />
Employee Id: <xsl:value-of select="EmployeeId" /><br />
Employee Name: <xsl:value-of select="LastName" />,<xsl:value-of select="FirstName" /><br />
</xsl:template>
<xsl:template match="Employee">
<br />
Manager Id: <xsl:value-of select="EmployeeId" /><br />
Manager Name: <xsl:value-of select="LastName" />,<xsl:value-of select="FirstName" /><br />
Department Name: <xsl:value-of select="DepartmentName" /><br />
Number of Staff: <xsl:value-of select="NumberOfStaff" /><br />
</xsl:template>
</xsl:stylesheet>
期望的输出
COMPANY INFO
Company Id: 1
Company Name: Company B
EMPLOYEES
Employee Id: 1
Employee Name: Doe,Jane
Employee Id: 2
Employee Name: Smith,James
MANAGERS
Manager Id: 3
Manager Name: Johnson,Michael
Department Name: Sales
Number of Staff: 20
Manager Id: 2
Manager Name: Smith,James
Department Name: IT
Number of Staff: 50
答案 0 :(得分:6)
您可以在模板
的匹配属性中指定父级对于经理......
<xsl:template match="Managers/Employee">
对于员工......
<xsl:template match="Employees/Employee">
请注意,虽然不一定在这种情况下,另一种选择是使我们成为&#34;模式&#34;
<xsl:apply-templates select="/Company/Employees/Employee" mode="Employees" />
<xsl:apply-templates select="/Company/Managers/Employee" mode="Managers" />
然后你可以像这样编写模板匹配:
<xsl:template match="Employee" mode="Employees">
<xsl:template match="Employee" mode="Managers">