Reputation: 2995
I am parsing an xml file and am running into an issue when trying find a node that has an apostrophe in it. When item name does not have this everything works fine. I have tried replacing the apostrophe with different escape chars but am not having much luck
string s = "/itemDB/item[@name='" + itemName + "']";
// Things i have tried that did not work
// s.Replace("'", "''");
// .Replace("'", "\'");
XmlNode parent = root.SelectSingleNode(s);
I always receive an XPathException. What is the proper way to do this. Thanks
Upvotes: 3
Views: 1717
Reputation: 2106
You can do it Like this:
XmlDocument root = new XmlDocument();
root.LoadXml(@"<itemDB><item name=""abc'def""/></itemDB>");
XmlNode node = root.SelectSingleNode(@"itemDB/item[@name=""abc'def""]");
Note the verbatim string literal '@' and the double quotes.
Your code would then look like this and there is no need to replace anything:
var itemName = @"abc'def";
string s = @"/itemDB/item[@name=""" + itemName + @"""]";
Upvotes: 1