I want to Copy Whole Word document Content to XML in C#

Dani AI

Generated

asked for a way to copy a Word document to XML. and pointed toward Word/Office-based automation; that works interactively but has important limits (especially on servers). Below are practical, modern options and small C# examples you can apply right away.

If the file is .docx (Open XML), the document body is already XML inside the package. The safest programmatic route is the Open XML SDK rather than automating Word. A minimal example to read the main document XML:

using DocumentFormat.OpenXml.Packaging;

string GetDocumentXml(string docxPath)
{
    using (var doc = WordprocessingDocument.Open(docxPath, false))
    {
        return doc.MainDocumentPart.Document.OuterXml;
    }
}

That returns the WordprocessingML for the main document. To create a simpler, content-only XML (paragraphs as elements), use LINQ to XML:

using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Linq;

XDocument ExtractParagraphs(string path)
{
    using (var doc = WordprocessingDocument.Open(path, false))
    {
        var paras = doc.MainDocumentPart.Document.Body
                       .Elements<Paragraph>()
                       .Select((p,i) => new XElement("p", new XAttribute("i", i), p.InnerText));
        return new XDocument(new XElement("document", paras));
    }
}

Notes and troubleshooting: images, headers/footers, footnotes and comments live in separate parts/relationships — saving only document.xml will not include binaries; copy related parts or extract needed content. If you must handle legacy .doc (binary) files, convert them to .docx first (client-side Word, LibreOffice headless, or a library that supports .doc). Avoid using Office automation on server processes — Microsoft does not support server-side Office automation. See the Open XML SDK docs for details and examples: Open XML SDK documentation and Microsoft guidance on Office automation on servers: .

Recommended Answers

All 2 Replies

>I want to Copy Whole Word document Content to XML in C#

Office Interop API.

As adatapost pointed out, you should use Office Interop API to open the document using Microsoft Word and the use SaveAs() as XML and you're done. It's just couple of lines of code. Just get used with Office Interop API. It's a lot of fun to me (in the most cases :) ).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.