Arxeiss
Arxeiss

Reputation: 1046

C# cannot save apostrophe to XML

I tried to save apostrophe ' to XML, but always I get an error.

When I want to save new item, first I tried to find it. I use this

XmlNode letters = root.SelectSingleNode("//letters");
XmlNode oldFileLetter = letters.SelectSingleNode("letter[@name='"+letterName+"']");

but when letterName contains apostrophe ' I get an error, that path isn't closed

I also found this c# parsing xml with and apostrophe throws exception but when I did what Steven said, it's OK for apostrophe, but double quotes throw exception.

I need to pass " and ' too.

Upvotes: 3

Views: 1941

Answers (5)

JLRishe
JLRishe

Reputation: 101700

The issue here is that your XPath already has an apostrophe indicating the beginning of a string within the XPath, so any apostrophe in your letterName value would be interpereted as closing the string value.

Contrary to Felipe's advice, XPaths are not themselves XML, so replacing the apostrophes with ' will not work. It will avoid the error, but you won't find the node you're looking for if letterName contains an apostrophe. Also, there is no difference in C# between "'" and "\'", so that will not help either.

I'd suggest looping through the letter elements and identifying the one where @name has the value you're looking for:

XmlNode oldFileLetter = null;
foreach(XmlNode letterNameNode in letters.SelectNodes("letter/@name"))
{
    if(letterNameNode.Value.Equals(letterName))
    {
        oldFileLetter = letterNameNode.ParentNode;
        break; 
    }
}

The only other approach I know of involves rigging up a system to allow defining and using XPath variables in your paths, but that's usually overkill.

Upvotes: 1

Zeddy
Zeddy

Reputation: 2089

You have to write it as an entity i think... I'm,not sure but i can recall having come across this issue once before.

Look at this wikipedia thread... http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

Upvotes: 1

devilkkw
devilkkw

Reputation: 438

const string apo = "\'";
XmlNode letters = root.SelectSingleNode("//letters");
XmlNode oldFileLetter = letters.SelectSingleNode("letter[@name="+apo+letterName+apo+"]")

Upvotes: 0

Felipe Oriani
Felipe Oriani

Reputation: 38608

You also could replace the apostriphe by '

letterName = letterName.Replace("'", "'");

XmlNode letters = root.SelectSingleNode("//letters");
XmlNode oldFileLetter = letters.SelectSingleNode("letter[@name='"+letterName+"']");

Take a look at this thread about special chars on a xml file.

Upvotes: 3

Marcus
Marcus

Reputation: 8669

Have you tried escaping it as such:

\'

Upvotes: 1

Related Questions