如果子节点使用xsl等于xslt中的特定值,如何选择父节点

时间:2017-09-22 08:44:29

标签: xml xslt xpath saxon

我的XML看起来像

sizeof

我需要获取id = Maths的主题并将其sid更改为22(或requried value)。相似的我需要得到id为科学的主题,并将其sid更改为23以及其他不能正常工作**

1 个答案:

答案 0 :(得分:0)

根据问题中提供的其他输入,解决方案已经过修改,现在可以用来将<sid>中的值替换为不同文件中的值。

<强> File1.xml

<Subjects>
    <subject>
        <id>Maths</id>
        <sid>12</sid>
    </subject>
    <subject>
        <id>science</id>
        <sid>13</sid>
    </subject>
    <subject>
        <id>social</id>
        <sid>14</sid>
    </subject>
</Subjects>

<强> File2.xml

<inputfile>
    <mathsid>22</mathsid>
    <scienceid>23</scienceid>
    <socialid>24</socialid>
</inputfile>

XSLT使用逻辑从<id>读取File1.xml的值并从中创建一个节点即可。 <Mathsid><scienceid><socialid>。使用这个伪造的节点,它在File2.xml中查找包含相似名称的节点。匹配是从第二个字符完成的,因此<Mathsid>中的大写字母M不会与<mathsid>产生问题。它也可以通过将驼峰案例节点名称转换为小写来实现,但XSLT 1.0需要额外的工作来处理它。

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" />
    <xsl:strip-space elements="*" />

    <xsl:param name="file" select="document('File2.xml')/inputfile" />

    <!-- identity transform -->
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" />
        </xsl:copy>
    </xsl:template>

    <!-- for all 'subject' nodes -->
    <xsl:template match="subject">
        <!-- create variable to fabricate a node name i.e. Mathsid, scienceid, 
             socialid using the value in <id> and string 'id' -->         
        <xsl:variable name="subjNameNode" select="concat(id, 'id')" />
        <xsl:copy>
            <!-- copy the value of node id as is -->
            <xsl:apply-templates select="id" />
            <!-- replace existing value of 'sid' by value from the different file by checking
                 whether the node name contains the explicitly created above. The check is done 
                 from the 2nd character so that <mathsid> contains text 'athsid' -->
            <sid>
                <xsl:value-of select="$file/*[contains(local-name(), substring($subjNameNode,2))]" />
            </sid>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

File1.xml一起使用时,XSLT会对其进行转换并生成所需的输出。

<强>输出

<Subjects>
    <subject>
        <id>Maths</id>
        <sid>22</sid>
    </subject>
    <subject>
        <id>science</id>
        <sid>23</sid>
    </subject>
    <subject>
        <id>social</id>
        <sid>24</sid>
    </subject>
</Subjects>
相关问题