[英]c# parsing xml with and apostrophe throws exception
I am parsing an xml file and am running into an issue when trying find a node that has an apostrophe in it. 我正在解析一个xml文件,并在尝试查找其中包含撇号的节点时遇到问题。 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. 我总是收到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 + @"""]";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.