简体   繁体   中英

Replace strings in a word document by parsing JSON file in C#

I have been trying to replace the strings in a word document that comes from a JSON response. However, I do not have experience in C#.

The example of a JSON response:

[
  {
    "Animal": "Frog",
    "Human": "John"
  },
  {
    "Animal": "Horse",
    "Human": "Alice"
  }
]

The code that tries to replace in C#:

private void ReplaceWords(Stream stream, JArray jsonStream, string filePath)
{
    string finalWordDocument = null;
    string docText = null;
    WordprocessingDocument doc =
        WordprocessingDocument.Open(stream, true);
    using (doc)
    {
        using (StreamReader docxReader = new StreamReader(doc.MainDocumentPart.GetStream()))
        {
            docText = docxReader.ReadToEnd();
        }
        foreach (JObject item in jsonStream)
        {
            String animals = item.GetValue("Animal").ToString();
            String humans = item.GetValue("Human").ToString();
            Console.WriteLine(animals);
            Console.WriteLine(humans);
            finalWordDocument = docText.Replace(animals, humans);
        }

        Console.WriteLine(finalWordDocument.ToString());
        StreamWriter docxWriter = new StreamWriter(doc.MainDocumentPart.GetStream(FileMode.Create));
        using (docxWriter)
        {
            docxWriter.Write(finalWordDocument);
        }
    }
}

In the console.log for both animals and humans are obtained without a problem. However, when it comes to docText.Replace, it does not replace all the animals with humans. It only replaces the last animal with a human name. I can not see the error in the algorithm, as I do the replacement inside the loop, Shouldn't it replace all the occurrences?

Any help would be highly appreciated.

You replace the words in a loop, but you always use docText as the source. So when you want to replace the second animal, you again use docText where the first animal has not yet been replaced.

To solve that, you can set finalWordDocument = docText; before the foreach and always use finalWordDocument for the replacement:

finalWordDocument = finalWordDocument.Replace(animals, humans);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM