Runs splitting several times

0

Well guys, I'm having a problem that's disturbing me a bit, I've already tried it and found nothing that would help me.

I'm searching for certain variables in a Word Template to be able to perform a replacement. The problem occurs when some variables are broken into several Runs , for example:

NT:Inthisimageitisclearthatthevariablemunicipio_iglaisbrokenintwoRuns,withRun1=>munici,andRun2=>pio_sigla,portingwhensearchingforitcomplete(municipio_igla)willnotreturnanyresults.

Edit1:Hereisanexamplecode:

//PegandooscabeçalhosSearchAndReplace(partLists:document.MainDocumentPart.HeaderParts,target:"<municipio_sigla>", replace: municipio.Sigla);

//Método que procura e substitui as variáveis:
private static void SearchAndReplace<T>(IEnumerable<T> partLists, string target, string replace) where T : OpenXmlPart
{
        foreach (var part in partLists)
        {
            foreach (var currentParagraph in part.RootElement.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>())
            {
                foreach (var currentRun in currentParagraph.Descendants<DocumentFormat.OpenXml.Wordprocessing.Run>())
                {
                    foreach (var currentText in currentRun.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>())
                    {
                        if (currentText.Text.Contains(target))
                        {
                            currentText.Text = currentText.Text.ReplaceInsensitive(target, replace);
                        }
                    }
                }
            }
        }
}

Has anyone tackled anything like this? And if so, is there a solution?

    
asked by anonymous 21.11.2017 / 15:09

1 answer

1

Well guys, I was able to find a very interesting answer in the stackoverflow gringo where it said that variables of this type can be problematic , because OpenXml separates texts that have some special characters (<, >, @, #, $ ...). This response led me to this Simon Doodkin code .

It takes the Runs' texts and concatenates them into a string, searches for the value to be replaced, and replaces the positions of each character.

I ended up making a code to make it easy for me to do the replacements, and he finds himself here , for anyone who has interest ...

Example usage:

wordDoc.MainDocumentPart.Document.ReplaceInElement("from", "to");
    
22.11.2017 / 19:31