C # parsing xml c and apostrophe exception

I am parsing an xml file and run into a problem when trying to find a node that has an apostrophe in it. When the element name does not have this, everything works fine. I tried replacing the apostrophe with different escape characters, but I was not very lucky

string s = "/itemDB/item[@name='" + itemName + "']";

// Things i have tried that did not work
// s.Replace("'", "''");
// .Replace("'", "\'");

XmlNode parent = root.SelectSingleNode(s);

I always get an XPathException. What is the right way to do this. Thanks

+3
source share
2 answers

You can do it:

XmlDocument root = new XmlDocument();

root.LoadXml(@"<itemDB><item name=""abc'def""/></itemDB>");

XmlNode node = root.SelectSingleNode(@"itemDB/item[@name=""abc'def""]");

Note the shorthand literal '@' and double quotes.

Then your code will look like this and nothing needs to be replaced:

var itemName = @"abc'def";

string s = @"/itemDB/item[@name=""" + itemName + @"""]";
+1
source

To apostop, replace it with &apos;

+4
source

Source: https://habr.com/ru/post/1781035/


All Articles