首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过使用xslt比较另一个xml来更改元素值

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

Stack Overflow用户
提问于 2018-03-29 00:20:07
回答 2查看 406关注 0票数 0

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

我将整个xml2存储在一个变量中,我得到了一个寻找match="book“的模板,在这个模板中,我通过xml2变量解析它,并在xml1中匹配发布。如果匹配,则调用模板match=”xml2“,但是它在里面添加了新的标签,但不更新现有的标签。

XML-1

代码语言:javascript
复制
<books>
<book>
<name>abc</name>
<publication>triangle</publication>
<price></price>
</book>
<book>
<name>def</name>
<publication>rectangle</publication>
<price></price>
</book>
</books>

xml-2

代码语言:javascript
复制
<resource>
<prices>
<publication>triangle</publication>
<price>100</price>
<prices>
<prices>
<publication>rectangle</publication>
<price>200</price>
<prices>
</resource>

预期产出

代码语言:javascript
复制
<books>
    <book>
    <name>abc</name>
    <publication>triangle</publication>
    <price>100</price>
    </book>
    <book>
    <name>def</name>
    <publication>rectangle</publication>
    <price>200</price>
    </book>
    </books>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-29 10:57:09

你可以试试这个:

代码语言:javascript
复制
    <?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>
票数 0
EN

Stack Overflow用户

发布于 2018-03-29 10:37:03

代码语言:javascript
复制
<?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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49546170

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档