如何使用OpenXML在Word .docx中找到标签字符



背景:我有一个包含标签chars的Word .docx文档。我想阅读每个段落并替换一个空间。我需要这个空间作为定界符,以便我可以解析诸如日期,名称等之类的东西

问题:使用段是单独的XML元素。如果我手动替代空间,我的解析例程正常工作。但是,使用段落。Innertext返回的文本全部均匀。

我也无法使用run.innertext获得标签符。我搜索了示例,但没有发现解决问题的方法。

        using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(filePath, false))
        {
            Body body = wordDocument.MainDocumentPart.Document.Body;
            foreach (var para in body.Elements<Paragraph>())
            {
                s = para.InnerText.ToString();      // Tab chars are stripped
                Console.WriteLine("Run: " + s);
            }
        }
        using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(filePath, false))
            {
                Body body = wordDocument.MainDocumentPart.Document.Body;
                foreach (var para in body.Elements<Paragraph>())
                {
                    s = "";                 // Work string to build full line
                    foreach (var run in para.Elements<Run>())
                    {
                    //  If (This is a tab char)
                    //  { 
                    //     s = s + " ";     // Yes - Substitute a space 
                    //  }
                    //  else    // No - This assumes there are no other xml tags like "Proof Error"
                    //  {
                    //      s = s + run.InnerText.ToString();
                    //  }
                    }
                    Console.WriteLine("Run: " + s);
                }

已解决:我能够找到标签字符和替代空间。关闭。

我正在使用运行元素的.localname属性。我可以测试" tab"。

                    foreach (var e in run.Elements())
                    {
                        if (e.LocalName == "tab")
                        {
                            Console.WriteLine("    Element Tab: " + e.InnerText.ToString());
                            s = s + " ";
                        }
                        else if (e.LocalName == "t")
                        {
                            Console.WriteLine("    Element Text: " + e.InnerText.ToString());
                            s = s + e.InnerText.ToString();
                        }
                        else
                        {
                            Console.WriteLine("Drop Through RUN set: " + e.LocalName);
                        }
                    }

最新更新