如何使用 XSLT 在 XML 中设置属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17212489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 14:04:41  来源:igfitidea点击:

How to set attribute in XML using XSLT?

xmlxsltxpathxslt-2.0

提问by VextoR

For example, I want to add an attribute to this node:

例如,我想向这个节点添加一个属性:

<Party>

So it will look like:

所以它看起来像:

<Party role="this should be set using XPath">

Attribute value has to come from XPath.

属性值必须来自 XPath。

The following will not work :)

以下将不起作用:)

<Party role=<xsl:value-of select="some/xpath/path"/>>

How to do that?

怎么做?

回答by Ian Roberts

Attributes of literal result elements support the attribute value templatesyntax, using {}:

文字结果元素的属性支持属性值模板语法,使用{}

<Party role="{some/xpath/path}">

回答by Martin Honnen

<xsl:template match="Party">
  <Party role="{some/xpath/path}">
    <xsl:apply-templates select="@* | node()"/>
  </Party>
</xsl:template>

should do. As an alternative

应该做。作为备选

<xsl:template match="Party">
  <xsl:copy>
    <xsl:attribute name="role" select="some/xpath/path"/>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

Of course the apply-templates is only necessary if there are attribute and/or child nodes you also want to be processed (for example to be copied by an identity transformation template).

当然,仅当您还希望处理属性和/或子节点(例如,由身份转换模板复制)时,才需要应用模板。

回答by Shanjee

you can try the below sample:

您可以尝试以下示例:

<xsl:for-each select="YOUR_SELECT_PATH"> 
  <a> 
    <Party> <xsl:attribute name="role"><xsl:value-of select="@source"/></xsl:attribute> </Party>
    <xsl:value-of select="."/> 
  </a> 
</xsl:for-each> 

Here I am setting the attribute role to a xml node Party.

这里我将属性角色设置为 xml 节点 Party。