从C#代码重命名XSLT属性值

时间:2019-03-07 01:44:11

标签: c# .net xml xslt xpath

我的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";
                    }

此代码给我一个错误,无法分配属性名称,该属性名称是只读的。

enter image description here

有什么可能的解决方案?

编辑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>

1 个答案:

答案 0 :(得分: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"));
}