Merge 2 XML files and modifying the attribute values

前端 未结 2 1139
无人及你
无人及你 2021-01-21 10:21

I have two xml files. I want to merge them and make some arithmetic with a few attributes. Please provide some ideas. I am using a standard xslt http://informatik.hu-berlin.de/m

相关标签:
2条回答
  • 2021-01-21 10:53

    This transformation:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
    
     <xsl:param name="pFile1" select="'file:///c:/temp/delete/file1.xml'"/>
     <xsl:param name="pFile2" select="'file:///c:/temp/delete/file2.xml'"/>
    
     <xsl:variable name="vF2Cover" select="document($pFile2)/coverage"/>
    
     <xsl:template match="/">
       <xsl:apply-templates select="document($pFile1)/coverage"/>
     </xsl:template>
    
     <xsl:template match="coverage">
       <coverage branch-rate=
        "{(@branch-rate*@branch-total + $vF2Cover/@branch-rate*$vF2Cover/@branch-total)
          div (@branch-total+$vF2Cover/@branch-total)
         }"
       branch-total=
        "{@branch-total*(@branch-total>= $vF2Cover/@branch-total)
        +
         $vF2Cover/@branch-total*($vF2Cover/@branch-total >@branch-total)
         }"
       line-rate=
        "{@line-rate*($vF2Cover/@line-rate >= @line-rate)
        +
         $vF2Cover/@line-rate*(@line-rate > $vF2Cover/@line-rate)
         }"/>
     </xsl:template>
    </xsl:stylesheet>
    

    when applied on any XML document (not used), and having the two provided XML documents reside in:

    c:/temp/delete/file1.xml:

    <coverage branch-rate="0.5125" branch-total="50" line-rate="0.00593031875463">
    </coverage>
    

    and c:/temp/delete/file2.xml:

    <coverage branch-rate="0.5" branch-total="40" line-rate="1.0">
    </coverage>
    

    produces the wanted, correct result:

    <coverage branch-rate="0.5069444444444444" branch-total="50" line-rate="0.00593031875463" />
    
    0 讨论(0)
  • 2021-01-21 11:14

    You can use XSLT and the document function. Document loads another xml file into the xslt processing. The example does only a simple arithmetic operation. You need to modify it.

    <xsl:template match="coverage">
        <xsl:variable name="branchRateFromFile1" select="@branch-rate"/>
        <xsl:variable name="branchRateFromFile2" select="document(FILE2)/coverage/@branch-rate"/>
        <xsl:copy>
            <xsl:attribute name="branch-rate"><xsl:value-of select="number($branchRateFromFile1)+number($branchRateFromFile2)"/></xsl:attribute>
            <xsl:apply-templates select="*"/>
        </xsl:copy> 
    </xsl:template>
    
    0 讨论(0)
提交回复
热议问题