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
对于撇号,用'
替换它'
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 + @"""]";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.