简体   繁体   English

如何使用类似 json 格式的 C# open-xml SDK 从 Word 文档中获取文本?

[英]How to get text out of Word Document using C# open-xml SDK in json like format?

I'm trying to extract all the text from a word document using C# open-xml SDK, and I want to store the style attributes and innerText data from each of the paragraphs and then for each of the runs inside a paragraph (and eventually the same thing for the tables too).我正在尝试使用 C# open-xml SDK 从 word 文档中提取所有文本,并且我想存储每个段落的样式属性和 innerText 数据,然后存储段落内的每个运行(最终是桌子也一样)。

{
    "paragraphs": 
    [
        {
            "innerText": "",
            "runs": [
                {
                    "runProperties": {}, 
                    "innerText": ""
                }
            ],
            "paragraphProperties": {}
        }
    ],
    "tables":
    [
        {
​
        }
    ]
}

This is the desired structure.这是所需的结构。

I'm from python background where doing this using python dict would've been easy since there's no strict type for value of the key in a dict.我来自 python 背景,使用 python dict 执行此操作会很容易,因为 dict 中的键值没有严格的类型。 But I've got little to no idea on how to approach this in C#.但是我几乎不知道如何在 C# 中解决这个问题。

static void Main(string[] args)
        {
            string fileName = @"<path to file>";
​
            using (WordprocessingDocument myDoc = WordprocessingDocument.Open(fileName, true))
            {
                IEnumerable<Paragraph> paragraphList = myDoc.MainDocumentPart.Document.Body.Elements().Where(c => c is Paragraph).Cast<Paragraph>();
                foreach (Paragraph p in paragraphList)
                {
                    string paragraphInnerText = p.InnerText;
                    IEnumerable<Run> runList = p.ChildElements.Where(c => c is Run).Cast<Run>();
                    foreach (Run r in runList)
                    {
                        string runInnerText = r.InnerText;
                        IEnumerable<RunProperties> runProperties = r.ChildElements.Where(c => c is RunProperties).Cast<RunProperties>();
                        Console.WriteLine("Getting Run Data.");
                    }
                    IEnumerable<ParagraphProperties> paragraphPropertiesList = p.ChildElements.Where(r => r is ParagraphProperties).Cast<ParagraphProperties>();
                }
            }
            Console.WriteLine("All done. Press a key.");
        }

This is the code I've come up with so far, with some help.这是我到目前为止想出的代码,有一些帮助。

Any ideas on how can I store this in the json format, or how should I go about it?关于如何以 json 格式存储它的任何想法,或者我应该如何去做? Thanks in advance!提前致谢! :) :)

Option A, convert all document using source xml with SerializeXmlNode ( JSON.NET ):选项 A,使用带有 SerializeXmlNode ( JSON.NET ) 的源 xml 转换所有文档:

XmlDocument doc = new XmlDocument();
doc.LoadXml(myDoc.MainDocumentPart.Document.OuterXml);
var json = JsonConvert.SerializeXmlNode(doc);

Option B, create anonymus type for all paragraph and run's:选项 B,为所有段落和运行创建匿名类型:

IEnumerable<Paragraph> paragraphList = myDoc.MainDocumentPart.Document.Body.Elements().OfType<Paragraph>();
var proj = paragraphList.Select(p => p.ChildElements.OfType<Run>().Select(r => new
{
    r.InnerText,
    runProperties = r.ChildElements.OfType<RunProperties>().FirstOrDefault()?.Select(rp => new { rp.GetType().Name, Val = rp.GetAttributes().FirstOrDefault().Value })
}));
var json = JsonConvert.SerializeObject(proj, Newtonsoft.Json.Formatting.Indented);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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