poco
poco

Reputation: 2995

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. 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

Answers (2)

Steven K.
Steven K.

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

Madhur Ahuja
Madhur Ahuja

Reputation: 22701

For apostophe replace it with &apos;

Upvotes: 4

Related Questions