0

How can I change the root element name from <DocumentElement> to <table name = "UnknownTable"> when saving a DataTable to XML?

This is my code to create the xml file from the database:

peter = new MySqlCommand(cmd.CommandText, con);
                con.Open();
                dt = new DataTable("row");
                sda = new MySqlDataAdapter(peter);
                sda.Fill(dt);
                saveFileDialog1.Title = "Ticket speichern";
                saveFileDialog1.Filter = "XML-File | *.xml";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Encoding = Encoding.UTF8;
                    settings.Indent = true;
                    settings.NewLineOnAttributes = true;
                    using (XmlWriter xmlWriter = XmlWriter.Create(saveFileDialog1.FileName, settings))
                    {
                        dt.WriteXml(xmlWriter);
                        xmlWriter.Close();
                    }
                }

this is the created document:

enter image description here

1 Answer 1

1

The simplest way is to write the DataTable to a temporary XDocument, then rename the root element and add the necessary attribute(s). The following extension method does the job:

public static class DataTableExtensions
{
    public static void WriteXml(this DataTable dt, XmlWriter writer, XName rootName, IEnumerable<XAttribute> rootAttributes = null)
    {
        if (dt == null || writer == null || rootName == null)
            throw new NullReferenceException();

        var doc = new XDocument();
        using (var docWriter = doc.CreateWriter())
        {
            dt.WriteXml(docWriter);
        }
        if (doc.Root != null)
        {
            doc.Root.Name = rootName;
            if (rootAttributes != null)
                doc.Root.Add(rootAttributes);
        }
        doc.WriteTo(writer);
    }
}

Then use it like:

                dt.WriteXml(xmlWriter, "table", new[] { new XAttribute("name", "UnknownTable") });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.