using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using System.IO; using System.Xml.Linq; public void AddXDocumentToWordDocument(string filePath, XDocument xDoc) { // Open the Word document using (WordprocessingDocument document = WordprocessingDocument.Open(filePath, true)) { MainDocumentPart mainPart = document.MainDocumentPart; // Clear the existing content mainPart.Document.Body.RemoveAllChildren(); // Add the new content using PutXDocument function mainPart.PutXDocument(xDoc); } }
using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using System.IO; using System.Xml.Linq; public void CreateWordDocumentWithXDocumentContent(string filePath, XDocument xDoc) { // Create a new Word document using (WordprocessingDocument document = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document)) { // Create the MainDocumentPart MainDocumentPart mainPart = document.AddMainDocumentPart(); // Create the document structure using PutXDocument function mainPart.PutXDocument(xDoc); } }This example demonstrates how to create a new Word document with an XDocument as content. The function creates a new Word document and adds a MainDocumentPart. It then uses the PutXDocument function to insert the XDocument as the content of the document. Package Library: DocumentFormat.OpenXml In conclusion, MainDocumentPart PutXDocument is a useful function for updating or creating Word documents using an XDocument. It is part of the DocumentFormat.OpenXml package library in C#.