更新:我仍然有这个问题,更好的解释。
我有一个 XElement 列表,我正在遍历它们以检查它是否与正则表达式模式匹配。如果有匹配,我需要在不影响他的子元素的情况下替换当前元素的值。
例如,
<root>{REGEX:@Here}<child>Element</child> more content</root
在这种情况下,我需要替换根元素下的 {REGEX:@Here} 而不是子元素!如果使用:
string newValue = xElement.ToString();
if(ReplaceRegex(ref newValue))
xElement.ReplaceAll(newValue);
我丢失了子元素,标签被转换为值中的 & lt;child & gt; 元素。如果我使用:
xElement.SetValue(newValue);
xElement 的值将是,
"{REGEX:Replaced} Element more content"
因此也会丢失子元素。
如果正则表达式模式位于根元素或子元素下,我该怎么做才能替换将保留子元素并起作用的值。
PS:我将在这里添加正则表达式功能以供理解
private bool ReplaceRegex(ref string text)
{
bool match = false;
Regex linkRegex = new Regex(@"\{XPath:.*?\}", System.Text.RegularExpressions.RegexOptions.Multiline);
Match m = linkRegex.Match(text);
while (m.Success)
{
match = true;
string substring = m.Value;
string xpath = substring.Replace("{XPath:", string.Empty).Replace("}", string.Empty);
object temp = this.Container.Data.XPathEvaluate(xpath);
text = text.Replace(substring, Utility.XPathResultToString(temp));
m = m.NextMatch();
}
return match;
}