0

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 :/

4
  • 12
    Use an xml parser to parse xml not Regex. Commented Nov 13, 2012 at 19:30
  • 2
    Try XPath it's a much better approach than RegEx. Commented Nov 13, 2012 at 19:31
  • 2
    Yep. Agree with @L.B. There are plenty of XML tools out there. Don't pick the wrong tool for the job. Commented Nov 13, 2012 at 19:32
  • 1
    Or, to put it another way - anytime you're thinking of XML as a string, you're doing something wrong. Yes, you'll usually find it (in a readable from) as a string, but that's not how you should be dealing with it. Commented Nov 13, 2012 at 20:18

3 Answers 3

2
var doc = XDocument.Parse(xmlstring);
var value = doc.XPathSelectElement("//usr_clan_id").Value;
Sign up to request clarification or add additional context in comments.

Comments

2

Simplest solution

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

2 Comments

I suggest Int32.TryParse because there is no way to be sure that there will be just digits in the value.
@slosd yes, if it is possible to have non-integer value in this tag, then Int32.TryParse((string)xdoc.Element("usr_clan_id"), out value) will do the job without exception.
0

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>$"

4 Comments

Where would you pick as a sensible cut-off point? If people treat "short" pieces of XML as strings, when should they stop doing so?
As soon as attributes, namespaces or more than one element are involved regex is no good. It would be interesting though if the parser has any overhead compared to a regex match.
So, at a point where the lead in portion is an exact, known string. So you can accomplish the transform with cheaper string comparisons and substring operations, rather than regex?
Yes. You are of course totally right that regex is not the cheapest approach here, but asuming that Razor isn't all that interested in high performance I would favor readability over performance. As long as this code isn't executed n hundredthousand times it doesn't even matter if you care about performance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.