Razor
Razor

Reputation: 1

C# regex filtering

I need to get value of XML:

<usr_clan_id>123</usr_clan_id>

I need get 123, its example. I'll tried to use:

Match match = Regex.Match(input, @"<usr_clan_id>([0-9])</usr_clan_id>$",
RegexOptions.IgnoreCase);

But it's bad :/

Upvotes: 0

Views: 235

Answers (3)

slosd
slosd

Reputation: 3464

If you get a huge XML file, use a parser and get the value with XPath as suggested in the comments. If you only get the short XML string you included in your question, RegEx is perfectly fine in my opinion.

About the regular expression: You only match one digit. Instead use + which matches one or more digits.

@"<usr_clan_id>([0-9]+)</usr_clan_id>$"

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Simplest solution

XDocument xdoc = XDocument.Parse(@"<usr_clan_id>123</usr_clan_id>");
int id = (int)xdoc.Element("usr_clan_id");

Upvotes: 2

L.B
L.B

Reputation: 116108

var doc = XDocument.Parse(xmlstring);
var value = doc.XPathSelectElement("//usr_clan_id").Value;

Upvotes: 2

Related Questions