【发布时间】:2016-01-06 20:18:51
【问题描述】:
有没有办法选择性地将 XElement 内容替换为其他 XElement?
我有这个 XML:
<prompt>
There is something I want to tell you.[pause=3]
You are my favorite caller today.[pause=1]
Have a great day!
</prompt>
我想把它渲染成这样:
<prompt>
There is something I want to tell you.<break time="3s"/>
You are my favorite caller today.<break time="1s"/>
Have a great day!
</prompt>
我需要用实际的 XElement 替换占位符,但是当我尝试更改 XElement 的内容时,.NET 当然会转义所有尖括号。我理解为什么内容通常需要正确转义,但我需要绕过该行为并将 XML 直接注入内容中。
这是我原本可以使用的代码。
MatchCollection matches = Regex.Matches(content, @"\[(\w+)=(\d+)]");
foreach (XElement element in voiceXmlDocument.Descendants("prompt"))
{
if (matches[0] == null)
continue;
element.Value = element.Value.Replace(matches[0].Value, @"<break time=""5s""/>");
}
这是一项正在进行的工作,所以不要太担心 RegEx 模式的有效性,因为我稍后会解决这个问题以匹配多个条件。这是概念验证代码,重点是替换所描述的占位符。我在这里只包含了迭代和 RegEx 代码来说明我需要能够对已经填充了内容的整个文档执行此操作。
【问题讨论】: