Merge 2 XML files and modifying the attribute valu

2020-04-16 03:48发布

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/merge to merge the files.

File 1:

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

File 2:

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

Expected Result File

<coverage branch-rate="(0.5125*50 + 05*40)/(50+40)" branch-total="50" line-rate="0.00593031875463"> 
</coverage> 

标签: xml xslt merge
2条回答
在下西门庆
2楼-- · 2020-04-16 04:07

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>
查看更多
Ridiculous、
3楼-- · 2020-04-16 04:19

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" />
查看更多
登录 后发表回答