c# - 正则表达式 包含在 XML 元素中

标签 c# regex xml

如何在正则表达式中使用“contains”(“Contains”或“%like%”)?

我有一个正则表达式来将 XML 节点与精确文本进行匹配:

<([\w]+)[^>]*>sample<\/\1>

它生成准确的节点名称,但我想像 C# 和 SQL 中那样应用正则表达式 (%LIKE%)。

文字:

    <Part>this is sample part</Part>
    <Remarks>this is sample remark</Remarks>
    <Notes>this is sample notes</Notes>
    <Desc>sample</Desc>

预期的正则表达式结果应返回上述所有节点,但目前仅返回最后一个节点。

我创建了a sample here to test .

最佳答案

您可以使用XDocument像这样解析 XML:

var s = @"<?xml version=""1.0""?>
  <root>
    <Part>this is sample part</Part>
    <Remarks>this is sample remark</Remarks>
    <Notes>this is sample notes</Notes>
    <Desc>sample</Desc>
  </root>";
var document = XDocument.Parse(s);
var names = document.Descendants()
               .Elements()
               .Where(x => x.Value.Contains("sample")) // all nodes with text having sample
               .Select(a => a.Name.LocalName); // return the local names of the nodes
Console.WriteLine(string.Join("\n", names));

它打印:

enter image description here

使用 XPath 也可以实现同样的效果:

var names2 = document.Root.XPathSelectElements("//*[contains(text(), \"sample\")]");
var results = names2.Select(x => x.Name.LocalName));

要在 XML 无效的情况下回退到正则表达式,请使用

<(?:\w+:)?(\w+)[^<]*>[^<]*?sample[^<]*</(?:\w+:)?\1>

请参阅regex demo 。请注意(?:\w+:)?匹配打开和关闭标记节点中的任意 namespace 。 [^<]匹配除 < 之外的任何字符,所以不会溢出到下一个节点。

关于c# - 正则表达式 包含在 XML 元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44387603/

相关文章:

c# - 从 MySQL 服务器删除多条记录的最有效方法是什么?

c# - 有没有办法从属性测量 C# 函数执行时间?

c# - 如何在 XAML 中定义的 Canvas 子 UIElement 上方的 Canvas 上显示绘图视觉

方法的 C# 字符串表示

javascript - 使用正则表达式重命名对象数组的键

正则表达式包含全部且仅

regex - 在正则表达式的特定点过滤输入量?

java - 将java的xml Element对象转换为文本

xml - 需要根据两个元素对节点进行分组并对第三个元素求和。 key ?多变的?

c# - 如何使用 C# 动态更改 XML 节点的属性