【发布时间】:2026-02-13 09:45:01
【问题描述】:
我是 XSLT 的新手,致力于 XML 到 XML 的转换。我想根据条件在xml中添加一个元素。
我有这个员工信息,要求为每个员工在元素内添加标签。
**Scenario1**
<Employee>
<Name>Check1</Name>
<Position>
<org>
<orgName>COMPANY</orgName>
<orgType>ABC</orgTyp>
<org>
</Position>
</Employee>
**Scenario2**
<Employee>
<Name>Nitesh</Name>
<Position>
<role>Consultant</role>
</Position>
</Employee>
**Scenario3**
<Employee>
<Name>Nitesh</Name>
</Employee>
我写了下面的代码,但它没有给我想要的输出。
`
<xsl:when test="not(xs:Position)">
<xsl:copy>
<!-- And everything inside it -->
<xsl:apply-templates select="@* | node()"/>
<!-- Add node -->
<xs:Position>
<xs:Organization>
<xs:Organization_Type>1<xsl:value-of select="$OrgType"/>
</xs:Organization_Type>
<xs:Organization_Code>2<xsl:value-of select="$OrgCode"/>
</xs:Organization_Code>
<xs:Organization_Name>3<xsl:value-of select="$OrgName"/>
</xs:Organization_Name>
</xs:Organization>
</xs:Position>
</xsl:copy>
</xsl:when>
<xsl:when test="xs:Position">
<xsl:variable name="element" select="xs:Position"/>
<xsl:choose>
<xsl:when test="not(xs:Position/xs:Organization/xs:Organization_Type='COMPANY')">
<xs:Organization>
<xs:Organization_Type>1<xsl:value-of select="$OrgType"/>
</xs:Organization_Type>
<xs:Organization_Code>2<xsl:value-of select="$OrgCode"/>
</xs:Organization_Code>
<xs:Organization_Name>3<xsl:value-of select="$OrgName"/>
</xs:Organization_Name>
</xs:Organization>
<xsl:copy-of select="$element"/>
</xsl:when>
</xsl:choose>
</xsl:when>`
【问题讨论】:
-
每种场景的预期结果是什么?
-
输出类似于场景 1
-
"输出类似于场景 1" 真的吗?所以你不想在场景#2 中输出
<role>Consultant</role>节点? -
抱歉,如果我的回复不清楚并且我想在位置标签内输出为 org 标签,并且如果在位置标签中已经存在任何其他值,那么在输出中我需要添加 org 标签,其他标签应该保留原封不动
标签: xml xslt xslt-1.0 xslt-2.0 transformation