如何从.odt文件中获取文本

Por*_*pek 6 c# odf odt aodl

我需要从C#中的odf文件(打开文档格式)中获取所有文本.我找到了AODL库,并安装了它.我访问了AODL的页面https://wiki.openoffice.org,找到了如何完成我需要的任务的例子,但它们都没有成功.由于我无法想象的原因,所有示例都构建了新文档,并且没有关于如何加载文档和获取所有文本(例如OpenXML)的示例.你们知道任何可以指导我的参考资料吗?

我的"尝试"

var doc = new AODL.Document.TextDocuments.TextDocument();
        doc.Load(@"C:\path/to/Sample.odt");
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何迭代doc文档.

Por*_*pek 4

最后,我想通了。这是我创建的用于提取所有文本的方法。也许不完整,因为我不知道构成 .odt 文件的所有部分。此方法获取页眉和页脚、文本框和段落,并将其与回车分隔符连接起来。您需要 AODL 包,可以通过包管理器控制台安装:PM> Install-Package AODL。并添加

using AODL.Document.TextDocuments;
using AODL.Document.Content;
Run Code Online (Sandbox Code Playgroud)

在你的程序的顶部。

/// <summary>
    /// Gets all plain text from an .odt file
    /// </summary>
    /// <param name="path">
    /// the physical path of the file
    /// </param>
    /// <returns>a string with all text content</returns>
    public String GetTextFromOdt(String path)
    {
        var sb = new StringBuilder();
        using (var doc = new TextDocument())
        {
            doc.Load(path);

            //The header and footer are in the DocumentStyles part. Grab the XML of this part
            XElement stylesPart = XElement.Parse(doc.DocumentStyles.Styles.OuterXml);
            //Take all headers and footers text, concatenated with return carriage
            string stylesText = string.Join("\r\n", stylesPart.Descendants().Where(x => x.Name.LocalName == "header" || x.Name.LocalName == "footer").Select(y => y.Value));

            //Main content
            var mainPart = doc.Content.Cast<IContent>();
            var mainText = String.Join("\r\n", mainPart.Select(x => x.Node.InnerText));

            //Append both text variables
            sb.Append(stylesText + "\r\n");
            sb.Append(mainText);
        }




        return sb.ToString();
    }
Run Code Online (Sandbox Code Playgroud)