问题
I am trying to update attribute's value in xml with attribute from another xml by matching attributes in both xmls.
xml1:
<?xml version="1.0" encoding="utf-8"?>
<Products>
<Product>
<List prodId="123456" sellId="">
</List>
</Product>
</Products>
xml2:
<?xml version="1.0" encoding="utf-8"?>
<Products>
<Product>
<info prodId="123456" sellId="121">
<qnty>4</qnty>
</info>
<info prodId="23456" sellId="890">
<qnty>1</qnty>
</info>
</Product>
</Products>
I need to node, in second xml by prodId attribute, and from that node I need to take the attribute sellId="890" and populate in first xml.
Desired output:
<?xml version="1.0" encoding="utf-8"?>
<Products>
<Product>
<List prodId="123456" sellId="890">
</List>
</Product>
</Products>
This is my xsl
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:param name="f1" select="'xml2.xml'"/>
<xsl:variable name="doc1" select="document($f1)"/>
<xsl:key name="k1" match="Products/Product/info" use="@prodId"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Products/Product/List">
<xsl:variable name="tprodId" select="@prodId"/>
<xsl:for-each select="$doc1">
<xsl:attribute name="sellId">
<xsl:value-of select="key('k1', $tprodId)/@sellId"/>
</xsl:attribute>
</xsl:for-each>
</xsl:template>
回答1:
I would suggest you do it this way:
<xsl:template match="List" >
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:variable name="tprodId" select="@prodId"/>
<xsl:for-each select="$doc1">
<xsl:copy-of select="key('k1', $tprodId)/@sellId"/>
</xsl:for-each>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
Or, if you prefer:
<xsl:template match="@sellId" >
<xsl:variable name="tprodId" select="../@prodId"/>
<xsl:for-each select="$doc1">
<xsl:copy-of select="key('k1', $tprodId)/@sellId"/>
</xsl:for-each>
</xsl:template>
来源:https://stackoverflow.com/questions/39251392/matching-and-updating-attributes-in-2-xmls