vendredi 28 août 2020

Comparing string variables and ignoring outside whitespace

I have this function (part of a C# .Net DLL) which locates XML elements with a specific value and replaces the text. It uses recursion:

   private bool ReplaceNameInXMLDocument(XElement pElement, string strOldName, string strNewName)
    {
        bool bReplaced = false;

        try
        {
            if (pElement.HasElements)
            {
                foreach (var pSubElement in pElement.Descendants())
                {
                    ReplaceNameInXMLDocument(pSubElement, strOldName, strNewName);
                }
            }
            else if (pElement.Value == strOldName)
            {
                pElement.Value = strNewName;
            }

            bReplaced = true;
        }
        catch (Exception ex)
        {
            SimpleLog.Log(ex);
        }

        return bReplaced;
    }

The only issue I have is related to whitespace. Imagine strOldName is Happy but in the XML data file the value there (for what ever reason) is Happy (it has an extra space). At the moment my comparison method is not locating the match because of the difference with whitepsace.

I realise I could change the else clause like this:

{
    string strExistingValue = pElement.Value.Trim();
    if(strExistingValue = strOldName)
    {
        ...
    }
}

But is there any other way that I can compare strOldName against the string element and automatically ignore outside whitespace? This is because I know that the variable strOldName has already been Trimmed. Is there a simpler comparison beyond my suggested adjustment?

Aucun commentaire:

Enregistrer un commentaire