我使用Open XML处理Word文档中的文本。我试图将某些运行分成单个单词(由空格分隔),以便仅在文本与关键词匹配时进一步处理。
foreach (var text in run.Elements<Text>()){
string t1 = text.Text;
if (t1.Contains("keyWord"))
{
// I need to split the run here so that I have 1 run per word so that I can
// Process the runs individually (and add bookmarks if additional conditions are met
}
}
有没有一种简单的方法以这种方式拆分运行?我找不到任何简单的东西。
答案 0 :(得分:0)
这对我有用,虽然我不太明白为什么你会把这些单词分成单独的运行的目的。
using (var wordDoc = WordprocessingDocument.Open(@"c:\test\test.docx", true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
var runs = mainPart.Document.Descendants<Run>().ToList();
foreach (Run run in runs)
{
var text = run.GetFirstChild<Text>();
if(text.Text.Contains("KEYWORD"))
{
string[] words = text.Text.Split(' ');
for(int i = 0; i < words.Count(); i++)
{
string word = words[i];
var newRun = (Run)run.Clone();
string newWord = word + (i < words.Count() ? " " : "");
Text newRunText = newRun.GetFirstChild<Text>();
newRunText.Space = SpaceProcessingModeValues.Preserve;
newRunText.Text = newWord;
run.Parent.InsertBefore(newRun, run);
}
run.Remove();
}
}
}
它的工作原理是检查关键字的Run的Text元素,将句子拆分为单个单词,然后克隆Run,并用单个单词替换文本。然后在旧的Run之前插入新的Run,完成后,删除旧的Run。 我必须为它添加SpaceProcessingModeValue以保留测试中的空间我使用包含句子&#34的简单.docx文件;这是搜索单词KEYWORD&#34;
希望它有所帮助。