ConsS
ConsS

Reputation: 25

Creating a XML file from a database with a model C#

So I need to create a method that makes an XML file from a database, I have already written the stored procedures that get the information from a database for the XML now I only need to write the part where I convert my database to a XML file using the properties of another class that I have written as nodes.

public string CreateXML(Object YourClassObject){    
      XmlDocument xmlDoc =new XmlDocument();   //Represents an XML document, 
                // Initializes a new instance of the XmlDocument class.          
      XmlSerializer xmlSerializer = new XmlSerializer(YourClassObject.GetType());            
    // Creates a stream whose backing store is memory. 
       using (MemoryStream xmlStream =new MemoryStream())
       { 
        xmlSerializer.Serialize(xmlStream, YourClassObject);
        xmlStream.Position = 0;
        //Loads the XML document from the specified string.
        xmlDoc.Load(xmlStream); 
        return xmlDoc.InnerXml;
       }
}

This is some code I found online I think I can use for serializing my model, but i'm accessing the database over an event that I created (I'll provide the code tomorrow when I get to work). Anyway I'm accesing the database in the event like the following e.DataTable. Any ideas anybody?

My model looks like the following:

public class DataModel
{
string Sifra {get; set;}
public string Naziv {get; set;}
public string JM {get; set;}
public int Kolicina {get; set;}
public float Cena_x0020_vp {get; set;}
public float Cena_x0020_mp {get; set;}
public float Cena_x0020_bod {get; set;}
public string Slika {get; set;}
public string Grupa {get; set;}
}

This is a sample of how my generated XML should look like.

<?xml version="1.0" encoding="UTF-8"?>

<dataroot xmlns:od="urn:schemas-microsoft-com:officedata" generated="2019-04-17T19:13:54">

<row>

<Sifra>ADA110-100</Sifra>

<Naziv_x0020_artikla>Adapter 220/110VAC 100W</Naziv_x0020_artikla>

<JM>kom</JM>

<Kolicina>1</Kolicina>

<Cena_x0020_vp>2683.33</Cena_x0020_vp>

<Cena_x0020_mp>3220</Cena_x0020_mp>

<Cena_x0020_bod>28</Cena_x0020_bod>

<Slika1> ada110v.jpg</Slika1>

<Grupa>Adateri 110V AC</Grupa>

</row>

Upvotes: 0

Views: 3186

Answers (4)

ConsS
ConsS

Reputation: 25

Problem solved:

    private void CreateXML(DataTable dataTable)
    {                   
        var list = new List<Row>();

        XmlSerializer writer = new XmlSerializer(typeof(List<Row>));

        var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ExportZaWeb.xml";
        FileStream file = File.Create(path);

        foreach (DataRow row in dataTable.Rows)
        {
            Row r = new Row();

            r.Naziv = row["Naziv Artikla"].ToString();
            r.JM = row["JM"].ToString();
            r.Kolicina = row["Kolicina"].ToString();
            r.Cena_x0020_vp = row["Cena vp"].ToString();
            r.Cena_x0020_mp = row["Cena mp"].ToString();
            r.Cena_x0020_bod = row["Cena bod"].ToString();
            r.Slika = row["Slika1"].ToString();
            r.Grupa = row["Grupa"].ToString();

            list.Add(r);
        }

        writer.Serialize(file, list);
        file.Close();
    }

Upvotes: 1

jdweng
jdweng

Reputation: 34421

Use XML Serializer :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication110
{
    class Program
    {
        const string INPUT_FILENAME = @"c:\temp\test.xml";
        const string OUTPUT_FILENAME = @"c:\temp\test1.xml";
        static void Main(string[] args)
        {
             XmlReader reader = XmlReader.Create(INPUT_FILENAME);

            string xml = reader.ToString();
            XmlSerializer serializer = new XmlSerializer(typeof(DataRoot));
            DataRoot root = (DataRoot)serializer.Deserialize(reader);

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(OUTPUT_FILENAME,settings);
            serializer.Serialize(writer, root);
        }
    }
    [XmlRoot(ElementName = "dataroot", Namespace = "")]
    public class DataRoot
    {
        [XmlElement(ElementName = "row", Namespace = "")]
        public List<DataModel> rows { get; set; }
    }
    [XmlRoot(ElementName = "row", Namespace = "")]
    public class DataModel
    {

        string Sifra { get; set; }
        public string Naziv { get; set; }
        public string JM { get; set; }
        public int Kolicina { get; set; }
        public float Cena_x0020_vp { get; set; }
        public float Cena_x0020_mp { get; set; }
        public float Cena_x0020_bod { get; set; }
        public string Slika { get; set; }
        public string Grupa { get; set; }
    }


}

Upvotes: 0

Matt Drouillard
Matt Drouillard

Reputation: 309

Create a method which takes in a list or IEnumerable object of the Models and returns a string containing the XML (untested, but should get you started), this is assuming you already have the database data in usable objects:

    public string GetXmlForModels(IEnumerable<DataModel> dataModels)
    {
        //Assume a list of DataModels is in dataModels of type IEnumerable<DataModel>
        var doc = new XmlDocument();
        foreach (var model in dataModels)
        {
            var row = (XmlElement)doc.AppendChild(doc.CreateElement("row"));
            row.SetAttribute("xmlns:od", "urn:schemas-microsoft-com:officedat");
            row.SetAttribute("generated", DateTime.Now.ToString("yy-MM-ddTHH:mm:ss"));

            var sifraElement = doc.CreateElement("Sifra");
            sifraElement.InnerText = model.Sifra;
            row.AppendChild(sifraElement);

            //Repeat top 3 lines for each element ...

            doc.AppendChild(row);
        }

        return doc.OuterXml;
    }

Upvotes: 0

Edney Holder
Edney Holder

Reputation: 1228

Why not let the stored procedure return the xml for you. The query in the stored procedure would lool something like this:

SELECT Sifra, Naziv, JM, Kolicina, Cena_x0020_vp, Cena_x0020_mp, Cena_x0020_bod, Slika, Grupa 
FROM DataModel
FOR XML AUTO

Upvotes: 0

Related Questions