Help selecting XML node value
-
Thursday, September 06, 2012 3:44 PM
Hello,
I need to select the value off a certain xml node, however one of the letters can be a-z:
<b:icdSource>database</b:icdSource>
Looking to just get the value but the letter b can be anything a-z
Thanks
All Replies
-
Friday, September 07, 2012 6:03 AM
Maybe this can help you:
<([a-z]:\w*)>(?<Value>.*?)</\1>
You can substitute \w* with your own tag name like this: <([a-z]:icdSource)>(?<Value>.*?)</\1>
This is the regex explanation for:
<([a-z]:\w*)>(?<Value>.*?)</\1>
Match the character “<” literally «<»
Match the regular expression below and capture its match into backreference number 1 «([a-z]:\w*)»
Match a single character in the range between “a” and “z” «[a-z]»
Match the character “:” literally «:»
Match a single character that is a “word character” (letters, digits, etc.) «\w*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the character “>” literally «>»
Match the regular expression below and capture its match into backreference with name “Value” «(?<Value>.*?)»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the characters “</” literally «</»
Match the same text as most recently matched by capturing group number 1 «\1»
Match the character “>” literally «>»Have a nice day.
Edit:
This is a possible implementation:
using System; using System.Text.RegularExpressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string testSubject = @"<b:icdSource>database</b:icdSource><x:icdServer>server</x:icdServer>"; Console.WriteLine(GetTagValue(testSubject, "icdSource")); Console.WriteLine(GetTagValue(testSubject, "icdServer")); } public static string GetTagValue(string xml, string tagName) { const string tagPatternFormat = @"<([a-z]:{0})>(?<Value>.*?)</\1>"; string tagPattern = string.Format(tagPatternFormat, tagName); var match = Regex.Match(xml, tagPattern); if (match.Success) { return match.Groups["Value"].Value; } return string.Empty; } } }
- Proposed As Answer by Romulus C Friday, September 07, 2012 6:06 AM
- Unproposed As Answer by Romulus C Friday, September 07, 2012 6:06 AM
- Edited by Romulus C Friday, September 07, 2012 6:22 AM Added sample code
- Proposed As Answer by Mike FengMicrosoft Contingent Staff, Moderator Friday, September 07, 2012 9:39 AM
- Marked As Answer by MKT44 Wednesday, September 12, 2012 2:11 PM
-
Wednesday, September 12, 2012 9:30 AM
I guess, using XElement will be more flexible way to retrieve value:
Imports <xmlns:b="your_name_space"> Module Test Sub Main() Dim xml = <root> <b:icdSource>database</b:icdSource> </root> Console.WriteLine(xml.<b:icdSource>.Value) Console.Write("Press any key to exit...") Console.ReadKey() End Sub End Module
There is no knowledge that is not power.
- Edited by JohnyL Wednesday, September 12, 2012 9:30 AM

