Runs splitting over and over

Asked

Viewed 43 times

0

Good guys, I’m having a problem that is disturbing me a little, I’ve searched about and found nothing to help me.

I’m researching certain variables in one Word Template to be able to perform a substitution. The problem occurs when some variables are broken into several Runs, for example:

Image do debug

NT: In this image it is clear that the variable municipio_acronym is broken in two Runs, being the Run1 => munici, and the Run2 => pio_acronym, So when searching it complete (municipio_acronym) will not return any result.

Edit1: Here’s an example of the code:

//Pegando os cabeçalhos
SearchAndReplace(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 ever faced such a thing? And if so, is there any solution?

  • 1

    It will be easier to help if you edit the question, including your code.

  • 'Cause it’s kkkkkkk. One moment.

  • @Leandroangelo, ready. I added an example code.

1 answer

1


Good guys, I managed to find a very interesting answer on stackoverflow gringo where it said that variables of this type can cause problems, because Openxml separates texts like this, which have some special character (<,>,@,#,$...). That answer led me to this Simon Doodkin’s code.

It takes the Runs text and concatenates into a string, looks for the value to be replaced and replaces it with the positions of each character.

I ended up making a code to facilitate me when making the replacements, and he finds here, for those interested...

Example of use:

wordDoc.MainDocumentPart.Document.ReplaceInElement("from", "to");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.