c# Regex on XML string handler
Trying to fiddle around with regex here, my first attempt. Im trying to extract some figures out of content from an XML tag. The content looks like this:
www.blahblah.se/maps.aspx?isAlert=true&lat=51.958855252721&lon=-0.517657021473527
I need to extract the lat and long numerical vales out of each link. They will always be the same amount of characters, and the lon may or may not have a "-" sign.
I thought about doing it like this below (its obviously not right though): (The string in question is in the "link" tag):
var document = XDocument.Load(e.Result);
if (document.Root == null)
return;
var events = from ev in document.Descendants("item1")
select new
{
开发者_开发百科 Title = (ev.Element("title").Value),
Latitude = Regex.xxxxxxx(ev.Element("link").Value, @"lat=(?<Lat>[+-]?\d*\.\d*)", String.Empty),
Longitude = Convert.ToDouble(ev.Element("link").Value),
};
foreach (var ev in events)
{
do stuff
}
Many thanks!
Try this:
Regex.Match(ev.Element("link").Value, @"lat=(?<Lat>[+-]?\d*\.\d*)").Groups[1].Value
Example:
string ev = "www.blahblah.se/maps.aspx?isAlert=true&lat=51.958855252721&lon=-0.517657021473527";
string s = Regex.Match(ev, @"lat=(?<Lat>[+-]?\d*\.\d*)").Groups[1].Value;
Result:
"51.958855252721"
If you have a URL with GET parameters, I would be tempted to find a library that can pull that apart for you, rather than using regexps. There may be edge cases that your regexp doesn't handle, but a library built for the specific purpose would handle (it depends on the set of data that you have to parse and how well-bounded it is, of course).
精彩评论