private string TranslateNodes(string html, string xpath) { if (_sourceLanguage == _targetLanguage) return html; var doc = new HtmlDocument(); doc.LoadHtml(html); HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes(xpath); if (nodes == null) return html; var translationRequest = new TranslationRequest(_sourceLanguage, _targetLanguage); foreach (var node in nodes) { if (!ShouldTranslateNode(node)) continue; translationRequest.Translations.Add(new Translation(FindTextToTranslate(node))); } // De-dupe list to minimize calls translationRequest.Translations = translationRequest.Translations.Distinct().ToList(); _translationProvider.Translate(translationRequest); foreach (var node in nodes) { if (!ShouldTranslateNode(node)) continue; Translation t = translationRequest.Translations.FirstOrDefault(x => x.SourceText == FindTextToTranslate(node)); if (t != null) WriteTranslatedText(node, t.TargetText); } return doc.DocumentNode.InnerHtml; }
private string Translate(string html) { if (_sourceLanguage == _targetLanguage) return html; var doc = new HtmlDocument(); doc.LoadHtml(html); HtmlNodeCollection textNodes = doc.DocumentNode.SelectNodes("//text()"); foreach (var textNode in textNodes) { string text = textNode.InnerHtml; if (string.IsNullOrWhiteSpace(text)) continue; if (ExcludeTags.Contains(textNode.ParentNode.Name.ToLower())) continue; var trans = new TranslationRequest(_sourceLanguage, _targetLanguage); trans.Translations.Add(new Translation(textNode.InnerHtml)); _translationProvider.Translate(trans); textNode.InnerHtml = trans.Translations[0].TargetText; } return doc.DocumentNode.InnerHtml; }