我只想更改某些特定元素的某些属性值。 例如,是否可以仅针对以下 XML 中价格为 29.99 的书籍更改 @lang?
<book>
<title lang="fr">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
最佳答案
这个简短的转换(根本没有明确的条件):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="book[price=29.99]/title/@lang">
<xsl:attribute name="lang">ChangedLang</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
当应用于提供的 XML 时(包装到格式良好的 XML 文档):
<t>
<book>
<title lang="fr">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</t>
产生想要的正确结果:
<t>
<book>
<title lang="ChangedLang">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</t>
说明:覆盖 identity rule 获取所需的属性。
关于xslt - 如何通过检查其同级的值来有条件地更改属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10282234/