除非您了解您的数据,否则使用正则表达式解析 XML 不是一个好主意。我会争辩说,在某些有限的情况下,它可能会很有帮助。@HighCore,请参阅同一个问题的答案。
我们并没有试图理解世界上所有可能的输入——我们试图做出在特定情况下有效的东西。因此,如果您知道您的输入没有<或> 在 data中,只有在节点名称中,您可以使用正则表达式。
在 C# 中,MatchEvaluator像这样使用:
class MyReplacer {
public string ReplaceSpaces(Match m)
{
return m.Value.Replace(" ", "_");
}
void replacingMethod() {
...
Regex re = new Regex("<.*>");
MyReplacer r = new MyReplacer();
// Assign the replace method to the MatchEvaluator delegate.
MatchEvaluator myEvaluator = new MatchEvaluator(r.ReplaceSpaces);
// Replace matched characters using the delegate method.
sInput = re.Replace(sInput, myEvaluator);
}