我正在尝试匹配 XML 文件上的特定术语并保存结果。以下是字符串上的 XML 文本:
<node1>
<node2>
<text>Goodbye</text>
</node2>
<node2>
<text>Welcome James</text>
</node2>
<node2>
<text>Welcome John</text>
</node2>
<node2>
<text>See you later!</text>
</node2>
</node1>
我想使用 linq 来选择任何欢迎的文本。但是,welcome 之后的名称(例如,welcome James)可以更改。因此,我试图了解是否有一种简单的方法可以通过正则表达式选择其中包含任何欢迎名称的节点?
这是 C# 代码:
private static void Test(string stream)
{
XDocument doc = XDocument.Parse(stream); //stream contains the xml written above
var list = from hello in doc.Descendants("node2")
where attacker.Element("text").Value == "Welcome .*"
select attacker.Element("text").Value;
foreach (var x in attackList)
Console.WriteLine(x);
}
最佳答案
对于像您这样简单的场景,无需使用正则表达式。您可以使用 String.StartsWith(String)判断字符串是否以指定字符串开头的方法如下:
private static void Test(string stream)
{
XDocument doc = XDocument.Parse(stream);
var list = from hello in doc.Descendants("node2")
where attacker.Element("text").Value.StartsWith("Welcome")
select attacker.Element("text").Value;
foreach (var x in attackList)
{
Console.WriteLine(x);
}
}
关于c# - where 子句的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6233372/