我正在尝试为其他人解决此问题,但我自己也遇到了问题。
我有 XML:
<Process>
<name>Pro1</name>
<duration>Dur1</duration>
<time>Time1</time>
<name>Pro2</name>
<duration>Dur2</duration>
<time>Time2</time>
<name>Pro3</name>
<duration>Dur3</duration>
<time>Time3</time>
<name>Pro4</name>
<duration>Dur4</duration>
<time>Time4</time>
<name>Pro5</name>
<duration>Dur5</duration>
<time>Time5</time>
</Process>
输出:
<Process>
<Process_Info>
<name>Pro1</name>
<duration>Dur1</duration>
<time>Time1</time>
</Process_Info>
<Process_Info>
<name>Pro2</name>
<duration>Dur2</duration>
<time>Time2</time>
</Process_Info>
<Process_Info>
<name>Pro3</name>
<duration>Dur3</duration>
<time>Time3</time>
</Process_Info>
<Process_Info>
<name>Pro4</name>
<duration>Dur4</duration>
<time>Time4</time>
</Process_Info>
<Process_Info>
<name>Pro5</name>
<duration>Dur5</duration>
<time>Time5</time>
</Process_Info>
</Process>
使用 XSLT:
<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 ="varProcess" select ="Process"/>
<xsl:template match="Process">
<xsl:element name="Process">
<xsl:for-each select ="name">
<xsl:variable name ="posName" select ="position()"/>
<xsl:element name ="Process_Info">
<xsl:copy-of select ="."/>
<xsl:copy-of select="$varProcess/duration[$posName]"/>
<xsl:copy-of select="$varProcess/time[$posName]"/>
</xsl:element>
</xsl:for-each>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
但是,<duration>
and<time>
节点并不总是存在,并且<name>
是唯一受保证的节点。因此,如果缺少一个,我的position()
选择就会失败。
如何更改 XSLT 以使其即使在<duration>
和/或<time>
不存在时也能正常工作。
我的理论是您选择当前名称节点下方的两个节点,如果它们是<duration>
或<time>
它们被复制?但也不确定这将如何实施。
导致问题的电流输出示例。
输入:
<Process>
<name>Pro1</name>
<duration>Dur1</duration>
<time>Time1</time>
<name>Pro2</name>
<duration>Dur2</duration>
<time>Time2</time>
<name>Pro3</name>
<duration>Dur3</duration>
<time>Time3</time>
<name>Pro4</name>
<time>Time4</time>
<name>Pro5</name>
<duration>Dur5</duration>
</Process>
输出:
<Process>
<Process_Info>
<name>Pro1</name>
<duration>Dur1</duration>
<time>Time1</time>
</Process_Info>
<Process_Info>
<name>Pro2</name>
<duration>Dur2</duration>
<time>Time2</time>
</Process_Info>
<Process_Info>
<name>Pro3</name>
<duration>Dur3</duration>
<time>Time3</time>
</Process_Info>
<Process_Info>
<name>Pro4</name>
<duration>Dur5</duration> <!-- Should be in the below process_info -->
<time>Time4</time>
</Process_Info>
<Process_Info>
<name>Pro5</name>
</Process_Info>
</Process>