Convert XML to Word, or XML to PDF in C#

Andrew Wilson
2 min readMay 10, 2024

--

The XML (Extensible Markup Language) a popular format for data exchange and storage. However, when it comes to sharing information with individuals who may not have access to applications that can read XML files, converting XML to more common formats such as MS Word (DOC/ DOCX) or PDF becomes necessary.

This article will guide you through how to convert XML to Word or PDF in C# using a free .NET library.

Introducing Free .NET Word Library

To converting XML to Word/ PDF programmatically in C#, we need the Free Spire.Doc for .NET library. You can either download the library from the below link to manually add reference to your project, or install it directly via NuGet.

Steps for Converting XML to Word (Doc/ Docx) or PDF

1. Import the necessary namespaces;

2. Create an instance of the Document class;

3. Load an XML file through the LoadFromFile method;

4. Save the XML file to a Doc/ Docx or PDF file using the SaveToFile method.

Convert XML to Word (Doc or Docx) in C#

using Spire.Doc;

namespace XMLtoWord
{
internal class Program
{
static void Main(string[] args)
{
//Load a Word document
Document document = new Document();
document.LoadFromFile(@"C:\Users\Administrator\Desktop\jellyfish.xml", FileFormat.Xml);

//Convert the XML file to a .doc file
document.SaveToFile("XMLToWord.doc", FileFormat.Doc);

//Convert the XML file to a .docx file
document.SaveToFile("XMLToWord.docx", FileFormat.Docx2016);
}
}
}

Output:

XML to Word in C#

Convert XML to PDF in C#

using Spire.Doc;

namespace XMLtoPDF
{
internal class Program
{
static void Main(string[] args)
{
//Load a Word document
Document document = new Document();
document.LoadFromFile(@"C:\Users\Administrator\Desktop\jellyfish.xml", FileFormat.Xml);

//Convert the XML file to a PDF file
document.SaveToFile("XMLToPDF.pdf", FileFormat.PDF);

}
}
}

Output:

XML to PDF in C#

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.