C#解析XML与和省略号引发异常 [英] c# parsing xml with and apostrophe throws exception
本文介绍了C#解析XML与和省略号引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我解析一个xml文件,并试图发现中有撇号的节点时,我遇到了一个问题。当项目名称没有这个一切工作正常。我曾尝试更换不同的逃逸字符的撇号,但我运气不好。
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);
我总是收到一个XPathException的。什么是做到这一点的正确方法。谢谢
I always receive an XPathException. What is the proper way to do this. Thanks
推荐答案
您可以做到这样的:
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 + @"""]";
这篇关于C#解析XML与和省略号引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文