I've got an XML in which I've got a number of nodes which contain paths, in which I (may) need to change some of the path if certain information is found.
For example, a node like this may exist:
<File name="dev\Desktop\Work开发者_StackOverflow社区ing\Test\English\1312\myopic.dll">
I need to find all paths that have a 4 digit number in the path (like '1312' above), and change this to something like %NUM%.
What's the best approach? My first thoughts were to use RegEx, but from some searching it seems like that's a bad idea?
Maybe LINQ to XML (I have some limited experience with that)?
I think that Regex here is the most effecint solution here, It is not bad idea at all
string path = @""<File name=""dev\Desktop\Working\Test\English\1312\myopic.dll"">";
string pattern = @"\d\d\d\d";
Regex regex = new Regex(pattern);
string replacement = "%NUM%";
string result = regex.Replace(input, replacement);
//result is: <File name="dev\Desktop\Working\Test\English\%NUM%\myopic.dll">
It is XML, so why not use XElement.
On the other hand, if this is a one-time thing and you want KNOW that the pattern won't occur in the wrong parts of your XML, regex would be much faster to implement.
newFileContents = Regex.Replace(
fileContents,
@"(?<=dev\\Desktop\\Working\\Test\\English\\)\d+",
"%num%);
精彩评论