这不算是一个问题,因为我已经找到了这个问题的原因。如下图所示,我正在尝试从OpenXml主体中检索后代元素:
使用以下代码检索后代元素:
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace Testolini
{
class Program
{
static void Main(string[] args)
{
var filename = Path.GetTempFileName();
var word = WordprocessingDocument.Create(filename, DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
word.AddMainDocumentPart();
word.MainDocumentPart.Document = new Document(
new Body(
new Paragraph(
new Run(
new Paragraph(
new Run(
new Text("test1"))),
new Paragraph(
new Run(
new Text("test2"))),
new Paragraph(
new Run(
new Text("test3")))))));
word.Close();
using (var memorystream = new MemoryStream(File.ReadAllBytes(filename)))
{
var word2 = WordprocessingDocument.Open(memorystream, true);
var descendants = word2.MainDocumentPart.Document.Body.Descendants();
word.Close();
}
}
}
}
如果你遇到了相同的问题,可能是因为XML文件不符合ECMA标准。在我的情况下,问题是由于我嵌套了段落。当我使用bytearray和memorystream打开文档时,问题就出现了。看起来元素已经被验证,如果验证失败,它会变成OpenXmlUnknownElement。如果有更好的解释或者更精确的原因,我很乐意学习更多。