XML/XSL:检查ID是否存在,然后将类添加到其他元素
如果我有这样的代码XML/XSL:检查ID是否存在,然后将类添加到其他元素,xml,xslt,Xml,Xslt,如果我有这样的代码 <code id="hello"> <tag> <moretags>...</moretags> </tag> </code> ... 与这样的代码相比: <code id="hello"> <tag> <moretags id="joker">...</moretags> </tag> </code> ... 我可以
<code id="hello">
<tag>
<moretags>...</moretags>
</tag>
</code>
...
与这样的代码相比:
<code id="hello">
<tag>
<moretags id="joker">...</moretags>
</tag>
</code>
...
我可以(在我的文件.xsl中)有这样一个规则:
如果id=“joker”出现(在带有file.xsl模板的HTML文件中)则将class=“world”添加到id=“hello”的东西中 如果是的话,这条规则会是什么样子 我:完全是新手。试着了解一些事情。试图向朋友解释我的意思。无法让人理解我自己。现在我知道如何表达我的问题了——朋友不在。希望你能帮助我。 浏览StackOverflow。。。但是,由于我几乎不知道如何界定我的问题,我不知道浏览什么。我敢肯定答案已经在这里的某个地方了(很可能对大多数人来说都很简单)。如果是,请链接。谢谢。在XSLT中,规则称为模板。因此,您需要编写一个与此元素匹配的模板:
<xsl:template match="*[@id = 'hello' and //*[@id='joker']]">
然后复制它并添加另一个属性:
<xsl:copy>
<xsl:attribute name="class" select="'world'"/>
但您还需要考虑该元素的其他属性,然后处理其余的节点
XML输入
<code id="hello">
<tag>
<moretags id="joker">...</moretags>
</tag>
</code>
<code id="hello" class="world">
<tag>
<moretags id="joker">...</moretags>
</tag>
</code>
...
样式表
<code id="hello">
<tag>
<moretags id="joker">...</moretags>
</tag>
</code>
<code id="hello" class="world">
<tag>
<moretags id="joker">...</moretags>
</tag>
</code>
此样式表中唯一的另一个模板规则是所谓的标识转换,它只生成输入XML的忠实副本
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="*[@id = 'hello' and //*[@id='joker']]">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:attribute name="class" select="'world'"/>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:transform>
XML输出
<code id="hello">
<tag>
<moretags id="joker">...</moretags>
</tag>
</code>
<code id="hello" class="world">
<tag>
<moretags id="joker">...</moretags>
</tag>
</code>
...
现在我知道如何表达我的问题了
我不会走那么远。。。但是,如果我们可以将问题重申为:
对于以下任何元素:•具有属性
id
=“hello”和•有一个属性为
id
=“小丑”的后代元素,添加一个属性
class
=“world”
然后你可以试试:
XSLT1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@id[.='hello'][..//@id='joker']">
<xsl:copy-of select="."/>
<xsl:attribute name="class">world</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
世界