使用XSLT合并2个XML文件并更改属性值

时间:2012-09-10 17:23:37

标签: xml xslt merge

  

可能重复:
  Merge 2 XML files and modifying the attribute values

我有两个xml文件。我想合并它们并使用一些属性进行一些算术运算。请提供一些想法。我使用标准的xslt http://informatik.hu-berlin.de/merge来合并文件。

文件1: coverage branch-rate =“0.5125”branch-total =“50”line-rate =“0.00593031875463”

文件2: coverage branch-rate =“0.5”branch-total =“40”line-rate =“1.0”

预期结果文件 coverage branch-rate =“(0.5125 * 50 + 05 * 40)/(50 + 40)”branch-total =“50”line-rate =“0.00593031875463”

1 个答案:

答案 0 :(得分:0)

我假设文件1和文件2都包含一个元素<coverage>,其中包含您提供的属性。我还假设总会有两个文件,而不是更多。我不确定所有计算对你的结果是如何起作用的,所以我猜。我使用了比必要更多的变量来使计算更简洁和可读。

在寻求帮助时你应该更明确。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">
        <xsl:variable name = "b1" select="document('file1.xml')/coverage"/>
        <xsl:variable name = "b2" select="document('file2.xml')/coverage"/>
        <xsl:variable name = "b1_br" select="$b1/@branch-rate"/>
        <xsl:variable name = "b1_bt" select="$b1/@branch-total"/>
        <xsl:variable name = "b1_lr" select="$b1/@line-rate"/>
        <xsl:variable name = "b2_br" select="$b2/@branch-rate"/>
        <xsl:variable name = "b2_bt" select="$b2/@branch-total"/>
        <coverage>
            <xsl:attribute name="branch-rate">
                <xsl:value-of select="(($b1_br * $b1_bt) + ($b2_br * $b2_bt)) div ($b1_bt + $b2_bt)"/>
            </xsl:attribute>
            <xsl:copy-of select="$b1/@branch-total"/>
            <xsl:copy-of select="$b1/@line-rate"/>
       </coverage>
     </xsl:template>
</xsl:stylesheet>