问题
Updating info in one XML file with optional info from another, using XSLT
If i change usa11.xml as:
<?xml version="1.0" encoding="UTF-8"?>
<country>
<state name="CA">
<city>
<street>
El Comino Ave.
</street>
<library>
library 11111.
</library>
</city>
<city>
<street>
DeAnza Ave.
</street>
<library>
library 22222.
</library>
</city>
<city>
<street>
shoreline Ave.
</street>
<library>
library 33333.
</library>
</city>
and usaa22.xml as:
<?xml version="1.0" encoding="UTF-8"?>
<country>
<state name="CA">
<city>
<street>
El Comino Ave.
</street>
<library>
library AAAAA.
</library>
</city>
<city>
<street>
DeAnza Ave.
</street>
<library>
library BBBBB.
</library>
</city>
then use usa22.xml's elements vaules to replace usa11.xml's ones ONLY if their street names are same: then get output usa33.xml like:
<?xml version="1.0" encoding="UTF-8"?>
<country>
<state name="CA">
<city>
<street>
El Comino Ave.
</street>
<library>
library AAAAA.
</library>
</city>
<city>
<street>
DeAnza Ave.
</street>
<library>
library BBBBB.
</library>
</city>
<city>
<street>
shoreline Ave.
</street>
<library>
library 33333.
</library>
</city>
</state>
Pls help advcie any idea how to do this??? Here "street" with value of "El Comino Ave."
will be used as a key or ID to find actual match in usa22.xml, then value of element "library" with value of "library 11111."
below the street element with the matched street value of "El Comino Ave." will be replaced by the same street value "El Comino Ave." but diff Library value of "library AAAAA." in usa22.xml to become "library BBBBB".
Pls help advcie any idea how to use xslt to do this???
Thanks
回答1:
Try something like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="u2" select="document('usaa22.xml')"/>
<xsl:template match="city">
<xsl:choose>
<xsl:when test="$u2//city[street=current()/street]">
<xsl:copy>
<xsl:apply-templates select="$u2//city[street=current()/street]/* " />
</xsl:copy>
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:apply-templates select="@* | node() " />
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="@* | node() " />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Which will generate the following output:
<country>
<state name="CA">
<city>
<street>
El Comino Ave.
</street>
<library>
library AAAAA.
</library>
</city>
<city>
<street>
DeAnza Ave.
</street>
<library>
library BBBBB.
</library>
</city>
<city>
<street>
shoreline Ave.
</street>
<library>
library 33333.
</library>
</city>
</state>
</country>
来源:https://stackoverflow.com/questions/16364771/updating-info-in-one-xml-file-with-optional-info-from-another-using-xslt