How to save a document in XML format using C# and .NET

  1. Add SautinSoft.Document from Nuget.
  2. Load or Create a document.
  3. Save to a XML format.

    In this code example, we will create a table and fill it with data. Next, we convert only tabular data to XML format.

If you need to convert non-tabular data, use the property: dc.Save(filePath, new XmlSaveOptions { ConvertNonTabularDataToSpreadsheet = true });

 

Complete code

using System;
using System.IO;
using System.Xml;
using SautinSoft.Document;
using SautinSoft.Document.Drawing;
using SautinSoft.Document.Tables;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free trial key here:   
            // https://sautinsoft.com/start-for-free/

            SaveToXmlFile();
        }

        /// <summary>
        /// Creates a new document and saves it as Xml file.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-xml-net-csharp-vb.php
        /// </remarks>
        static void SaveToXmlFile()
        {
            string inpFile = @"..\..\..\example.docx"; 
            string outFile = Path.ChangeExtension(inpFile, ".xml");

            var dc = DocumentCore.Load(inpFile);
            var xml = GetXml(dc);
            xml.Save(outFile);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }

        private static XmlDocument GetXml(DocumentCore dc)
        {
            var xml = new XmlDocument();
            var body = NewXmlNode(xml, xml, XmlNodeType.Element, "Document");

            foreach (Section section in dc.Sections)
            {
                var sec = NewXmlNode(xml, body, XmlNodeType.Element, "Section");
                WriteBlock(xml, sec, section.Blocks);
            }
            return xml;
        }

        private static void WriteBlock(XmlDocument xml, XmlNode parent, BlockCollection blocks)
        {
            foreach (var block in blocks)
            {
                switch (block)
                {
                    case Paragraph paragraph:
                        if (paragraph.Inlines.Count > 0)
                        {
                            var par = NewXmlNode(xml, parent, XmlNodeType.Element, "Paragraph");
                            foreach (var line in paragraph.Inlines)
                            {
                                switch (line)
                                {
                                    case Run run:
                                        var runNode = NewXmlNode(xml, par, XmlNodeType.Element, "Run");
                                        runNode.InnerText = run.Text;
                                        break;

                                    case ShapeBase shape:
                                        WriteDrawing(xml, par, shape);
                                        break;
                                }
                            }
                        }
                        break;
                    case Table table:
                        WriteTable(xml, parent, table);
                        break;
                }
            }
        }

        private static void WriteDrawing(XmlDocument xml, XmlNode parent, Element item)
        {
            if (item is ShapeGroup)
            {
                var shape = NewXmlNode(xml, parent, XmlNodeType.Element, "ShapeGroup");
                foreach (var sh in (item as ShapeGroup).ChildShapes)
                {
                    WriteDrawing(xml, shape, sh);
                }
            }
            else if (item is Picture)
            {
                var picture = NewXmlNode(xml, parent, XmlNodeType.Element, "Picture");
                var attr = xml.CreateAttribute("name");
                attr.Value = (item as Picture).Description;
                picture.Attributes.Append(attr);
            }
            else
            {
                var shape = NewXmlNode(xml, parent, XmlNodeType.Element, "Shape");
                var attr = xml.CreateAttribute("Figure");
                attr.Value = (item as Shape).Geometry.IsPreset ? ((item as Shape).Geometry as PresetGeometry).Figure.ToString() : "Custom";
                shape.Attributes.Append(attr);
                WriteBlock(xml, shape, (item as Shape).Text.Blocks);
            }
        }

        private static void WriteTable(XmlDocument xml, XmlNode parent, Table table)
        {
            var tab = NewXmlNode(xml, parent, XmlNodeType.Element, "Table");
            XmlAttribute attr = xml.CreateAttribute("rows");
            attr.Value = table.Rows.Count.ToString();
            tab.Attributes.Append(attr);
            attr = xml.CreateAttribute("cols");
            attr.Value = table.Columns.Count.ToString();
            tab.Attributes.Append(attr);
            for (int i = 0; i < table.Rows.Count; i++)
            {
                var row = NewXmlNode(xml, tab, XmlNodeType.Element, "Row");
                for (int j = 0; j < table.Rows[i].Cells.Count; j++)
                {
                    var cell = NewXmlNode(xml, row, XmlNodeType.Element, "Cell");
                    if (table.Rows[i].Cells[j].RowSpan > 1)
                    {
                        attr = xml.CreateAttribute("rowspan");
                        attr.Value = table.Rows[i].Cells[j].RowSpan.ToString();
                        cell.Attributes.Append(attr);
                    }
                    if (table.Rows[i].Cells[j].ColumnSpan > 1)
                    {
                        attr = xml.CreateAttribute("colspan");
                        attr.Value = table.Rows[i].Cells[j].ColumnSpan.ToString();
                        cell.Attributes.Append(attr);
                    }
                    WriteBlock(xml, cell, table.Rows[i].Cells[j].Blocks);
                }
            }
        }

        private static XmlNode NewXmlNode(XmlDocument xml, XmlNode parent, XmlNodeType type, string name)
        {
            XmlNode node = xml.CreateNode(type, name, null);
            parent.AppendChild(node);
            return node;
        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Document
Imports SautinSoft.Document.Tables

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			SaveToXmlFile()
		End Sub
                ''' Get your free trial key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' Creates a new document and saves it as Xml file.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-xml-net-csharp-vb.php
		''' </remarks>
		Private Shared Sub SaveToXmlFile()
			Dim dc As New DocumentCore()
			Dim db As New DocumentBuilder(dc)

			' Create a new table with preferred width.
			Dim table As Table = db.StartTable()
			db.TableFormat.PreferredWidth = New TableWidth(LengthUnitConverter.Convert(5, LengthUnit.Inch, LengthUnit.Point), TableWidthUnit.Point)

			' Specify formatting of cells and alignment.
			db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Green, 1)
			db.CellFormat.VerticalAlignment = VerticalAlignment.Top
			db.ParagraphFormat.Alignment = HorizontalAlignment.Center

			' Specify height of rows and write text.
			db.RowFormat.Height = New TableRowHeight(105F, HeightRule.Exact)
			db.InsertCell()
			db.Write("This is Row 1 Cell 1")
			db.InsertCell()
			db.Write("This is Row 1 Cell 2")
			db.InsertCell()
			db.Write("This is Row 1 Cell 3")
			db.EndRow()

			' Specify formatting of cells and alignment.
			db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Black, 1)
			db.CellFormat.VerticalAlignment = VerticalAlignment.Center
			db.ParagraphFormat.Alignment = HorizontalAlignment.Left

			' Specify height of rows and write text.
			db.RowFormat.Height = New TableRowHeight(150F, HeightRule.Exact)
			db.InsertCell()
			db.Write("This is Row 2 Cell 1")
			db.InsertCell()
			db.Write("This is Row 2 Cell 2")
			db.InsertCell()
			db.Write("This is Row 2 Cell 3")
			db.EndRow()

			' Specify formatting of cells and alignment.
			db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Orange, 1)
			db.CellFormat.VerticalAlignment = VerticalAlignment.Bottom
			db.ParagraphFormat.Alignment = HorizontalAlignment.Right

			' Specify height of rows and write text
			db.RowFormat.Height = New TableRowHeight(125F, HeightRule.Exact)
			db.InsertCell()
			db.Write("This is Row 3 Cell 1")
			db.InsertCell()
			db.Write("This is Row 3 Cell 2")
			db.InsertCell()
			db.Write("This is Row 3 Cell 3")
			db.EndRow()
			db.EndTable()

			' Save our document into XML format.
			Dim filePath As String = "Result.xml"
			dc.Save(filePath)

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(filePath) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.