I'm trying to match specific terms on a XML file and save the results. Here is the XML text on a string:
<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>
I want to use linq to select any text that has welcome in it. However the name after welcome (ex. welcome J开发者_运维知识库ames) can change. Thus, i'm trying to understand is there an easy way to select the nodes with any welcome name in it via regular expressions?
Here's the C# code:
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);
}
For a scenario as simple as yours there is no need to use regular expressions. You can use the String.StartsWith(String) method that determines whether a string starts with a specified string as follows:
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);
}
}
Regex regex = new Regex("Welcome");
XDocument doc = XDocument.Parse(stream); //stream contains the xml written above
var list = from hello in doc.Descendants("node2")
where regex.IsMatch(attacker.Element("text").Value)
select attacker.Element("text").Value;
The simplest way to get Regex matching is to use the static Regex.IsMatch(String, String)
function
If you want better performance, you can compile the regex beforehand (see proxon's answer).
As Marius mentions though, String.StartsWith is good enough for your specific example.
精彩评论