我有一个来自应用程序的相当大的 XML 输出。我需要用我的程序处理它,然后反馈给原来的程序。此 XML 中有些部分需要填写或替换。有趣的部分如下所示:
<sys:customtag sys:sid="1" sys:type="Processtart" />
<sys:tag>value</sys:tag>
here are some other tags
<sys:tag>value</sys.tag>
<sys:customtag sys:sid="1" sys:type="Procesend" />
并且该文档包含多个这样的部分。
我需要获取这些标签内的所有 XML 片段,以便能够对其进行修改。我写了一个正则表达式来获取这些片段,但它不起作用:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"output.xml");
Regex regExp = new Regex(@"<sys:customtag(.*?)Processtart(.*?)/>(.*?)<sys:customtag (.*?)Procesend(.*?)/>", RegexOptions.Multiline & RegexOptions.IgnorePatternWhitespace & RegexOptions.CultureInvariant);
MatchCollection matches = regExp.Matches(xmlDoc.InnerXml);
如果我将所有内容放在一行中并在没有多行选项的情况下调用此正则表达式,它确实会找到所有出现的地方。通过保留文件原样并设置多行选项,它不起作用。有什么问题,我应该改变什么?或者有没有更简单的方法在没有正则表达式的情况下获取这些标签之间的 XML 部分?
最佳答案
我相信要使用的选项是 RegexOptions.Singleline
而不是 RegexOptions.Multiline
( src )。允许 (.) 匹配换行符应该适用于您的情况。
...the mode where the dot also matches newlines is called "single-line mode". This is a bit unfortunate, because it is easy to mix up this term with "multi-line mode". Multi-line mode only affects anchors, and single-line mode only affects the dot ... When using the regex classes of the .NET framework, you activate this mode by specifying RegexOptions.Singleline, such as in Regex.Match("string", "regex", RegexOptions.Singleline).
关于c# - 无法使正则表达式与多行一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/289440/