【问题标题】:Renaming XSLT attribute value from C# code从 C# 代码重命名 XSLT 属性值
【发布时间】:2019-07-28 19:25:29
【问题描述】:

我有如下 XSLT:-

 <ServiceRequest ExternalSystemName="ServiceNow" Company="{ServiceRequest-Company}">
      <xsl:if test="{ServiceRequest-LastResolvedDate} and {ServiceRequest-LastResolvedDate} != ''" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:attribute name="LastResolvedDate">
          <xsl:value-of select="{ServiceRequest-LastResolvedDate}" />
        </xsl:attribute>
      </xsl:if>
      <xsl:if test="{ServiceRequest-ServiceType} and {ServiceRequest-ServiceType} != ''" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:attribute name="ServiceType">
          <xsl:value-of select="'SR'" />
        </xsl:attribute>
      </xsl:if>
...
...

我想通过 C# 代码重命名特定的属性名称。

为此我写了下面的代码:-

var property = root.Descendants(elementName).Descendants().Attributes("name").Where(x => x.Value == "LastResolvedDate");
                    foreach (var item in property)
                    {
                        item.Name = "renamed_new_name";
                    }

此代码给我的错误是属性名称无法分配并且是只读的。

可能的解决方案是什么?

编辑 1:

它正在更改属性名称:-

<xsl:if test="LastResolvedOn/value and LastResolvedOn/value != ''">
                    <xsl:attribute renamed_new_name="LastResolvedOn">
                      <xsl:value-of select="LastResolvedOn/value" />
                    </xsl:attribute>
                  </xsl:if>

我需要的地方:-

<xsl:if test="LastResolvedOn/value and LastResolvedOn/value != ''">
                    <xsl:attribute name="renamed_new_name">
                      <xsl:value-of select="LastResolvedOn/value" />
                    </xsl:attribute>
                  </xsl:if>

【问题讨论】:

    标签: c# .net xml xslt xpath


    【解决方案1】:

    您需要删除现有属性并添加一个新属性,例如:

    var elements = root.Descendants(elementName).Descendants()
        .Where(x => (string)x.Attribute("name") == "LastResolvedDate");
    
    foreach (var item in elements)
    {
        item.Attribute("name").Remove();
        item.Add(new XAttribute("renamed_new_name", "LastResolvedDate"));
    }
    

    【讨论】:

    • 你能看到Edit1吗?它正在重命名 name ,但我想重命名 name 的值 where name="LastResolvedOn"
    • @CSharper,在这种情况下只需执行item.Attribute("name").Value = "renamed_new_name";
    • @CSharper,顺便说一句,你的问题是Renaming XSLT attribute name from C# code,在这种情况下应该是changing attribute value
    • 完成。谢谢你注意到我。这个答案真的很有帮助
    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    相关资源
    最近更新 更多