标签:stack-overflow xpath linq-to-xml asp-net c
我有一个看起来像的XDocument
<root>
<a>
<b foo="1" bar="2" />
<b foo="3" bar="4" />
<b foo="5" bar="6" />
<b foo="7" bar="8" />
<b foo="9" bar="10" />
</a>
</root>
我希望将属性foo更改为其他内容,并将属性栏更改为其他内容.我如何轻松地做到这一点?我当前的版本(下面)堆栈中充满了大型文档,并且闻起来很可怕.
string dd=LoadedXDocument.ToString();
foreach (var s in AttributeReplacements)
dd = dd.Replace(s.Old+"=", s.New+"=");
解决方法:
这是完整的XSLT解决方案:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my:reps"
exclude-result-prefixes="my"
>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<my:replacements>
<foo1 old="foo"/>
<bar1 old="bar"/>
</my:replacements>
<xsl:variable name="vReps" select=
"document('')/*/my:replacements/*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@*">
<xsl:variable name="vRepNode" select=
"$vReps[@old = name(current())]"/>
<xsl:variable name="vName" select=
"name(current()[not($vRepNode)] | $vRepNode)"/>
<xsl:attribute name="{$vName}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
当此转换应用于提供的XML文档时,将产生所需的结果:
<root>
<a>
<b foo1="1" bar1="2"/>
<b foo1="3" bar1="4"/>
<b foo1="5" bar1="6"/>
<b foo1="7" bar1="8"/>
<b foo1="9" bar1="10"/>
</a>
</root>
请注意,这是一个通用解决方案,允许在不修改代码的情况下指定和修改任何替换列表.替换内容可以放在单独的XML文件中,以便于维护.
标签:stack-overflow,xpath,linq-to-xml,asp-net,c 来源: https://codeday.me/bug/20191024/1918131.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。