如何通过使用xslt比较另一个xml来更改元素值

时间:2018-03-29 00:20:07

标签: xml rest xslt web xslt-1.0

我有xml 1和xml2。我希望将xml1中的</publication>与xml2进行比较,并使用xml2中的值更新xml1中的<price>。请帮助我。

我已将整个xml2存储在一个变量中。我有一个模板,它查找match =&#34; book&#34;,在此我通过xml2变量解析它并匹配发布与xml1.If中的发布匹配,调用模板匹配=&#34;价格&#34;但 它在里面添加新标签但不更新现有标签。

XML-1

<books>
<book>
<name>abc</name>
<publication>triangle</publication>
<price></price>
</book>
<book>
<name>def</name>
<publication>rectangle</publication>
<price></price>
</book>
</books>

XML-2

<resource>
<prices>
<publication>triangle</publication>
<price>100</price>
<prices>
<prices>
<publication>rectangle</publication>
<price>200</price>
<prices>
</resource>

预期产出

<books>
    <book>
    <name>abc</name>
    <publication>triangle</publication>
    <price>100</price>
    </book>
    <book>
    <name>def</name>
    <publication>rectangle</publication>
    <price>200</price>
    </book>
    </books>

2 个答案:

答案 0 :(得分:0)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:param name="back" select="if (doc-available('b.xml')) then doc('b.xml') else ()"/>
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="book">
<book>
<xsl:apply-templates/>
</book>
</xsl:template>
<xsl:template match="name">
<name>
<xsl:apply-templates/>
</name>
</xsl:template>
<xsl:template match="publication">
<publication>
<xsl:apply-templates/>
</publication>
<price>
<xsl:if test="$back//publication = .">
<xsl:value-of select="$back//prices[. = publication]/price"/>
</xsl:if>
</price>
</xsl:template>
</xsl:transform>

答案 1 :(得分:0)

你可以试试这个:

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
<xsl:variable name="book1" select="document('file:////C://mohit//Untitled23.xml')/resource" as="node()"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>  
</xsl:template>
<xsl:template match="//price">
<xsl:variable name="pub" select="preceding-sibling::publication[1]"/>
<xsl:variable name="bk" select="$book1//price[preceding-sibling::publication[1] = $pub][1]"/>
<price>
<xsl:value-of select="$bk"/>
</price>
</xsl:template>
</xsl:stylesheet>