Replacing value in XML tags in C# using Regex -
i trying replace value between 2 xml tags default numeric value.
in following string, need replace value of dob w/ 1900-01-01.
input:
<firstname>test</firstname> <dob>test</dob> <tt:lastname>test</tt:lastname> <tt:dob>test</tt:dob>
desired output:
<firstname>test</firstname> <dob>1900-01-01</dob> <tt:lastname>test</tt:lastname> <tt:dob>1900-01-01</tt:dob>
this have:
string pattern = @"<((dob|tt:dob).*>).*?</\1"; string input = "<firstname>test</firstname><dob>test</dob><tt:lastname>test</tt:lastname><tt:dob>test</tt:dob>"; string replacement = "<$1 1900-01-01 </$1"; regex rgx = new regex(pattern); string result = rgx.replace(input, replacement);
which gives me:
<dob> 1900-01-01 </dob> <tt:dob> 1900-01-01 </tt:dob>
i'm able set default date, not without putting space between value , 1st subpattern in replacement variable. if take out spaces, reads "1900" part of first subpattern.
here link regex test: https://regex101.com/r/fk3ya5/6
is there way replace values number without using space or quotes?
jon skeet correct, should use xelement api. however, answer question, can follows changing replacement regex this:
string replacement = "<${1}1900-01-01 </$1";
notice how $1
became ${1}
. see here more details
Comments
Post a Comment