-1

I'm searching for a good way to generate an XML by a specific format. After checking several guids and SO questions(which I'm to newbie to understand most of them) I've encountered the XElement feature for buildig a "tree" .

This could work, according to the link, you can nest an XElement over and over and create the desired hierarchy. My problem is that I need to load records from my database.

So my question is - Is there a way to create an XElement which will be the ROOT, and then for each record from my table, create another XElement and populate all the necessary details, and then attach it to the original root? Or am I going in the wrong direction and there's an easier way around it.

recnac
  • 3,744
  • 6
  • 24
  • 46
  • 1
    What database? Quite a few have built-in XML support, saving you the trouble (for example, SQL Server's `FOR XML`). – Jeroen Mostert Jul 31 '18 at 12:18
  • 1
    Possible duplicate of [How can I build XML in C#?](https://stackoverflow.com/questions/284324/how-can-i-build-xml-in-c) – Liam Jul 31 '18 at 12:18
  • You may be interested in the DataTable's WriteXML method. https://msdn.microsoft.com/en-us/library/system.data.datatable.writexml(v=vs.110).aspx – JohnLBevan Jul 31 '18 at 12:20
  • You could just serialise an object too, there are a load of different ways to achieve this, the SQL FOR XML might be the easiest unless you really need to do this inside your library. – Charleh Jul 31 '18 at 12:25

1 Answers1

1

It's not a .NET Core specific issue. Why not using the FOR XML PATH clause in your SQL statement to get the XML formatted data like this:

SELECT * FROM Employee 
FOR XML PATH('Employee'), ROOT ('Employees')

More information can be found here: https://learn.microsoft.com/en-us/sql/relational-databases/xml/examples-using-path-mode?view=sql-server-2017

Bouke
  • 1,531
  • 1
  • 12
  • 21
  • Because I need it in a specific format, with many records grouped by with more than 1 hierarchy level , how can I achieve it with FOR XML PATH? –  Jul 31 '18 at 12:29
  • This is also possible with FOR XML PATH. Search for the term 'hierarchy' in the above mentioned Microsoft documentation. – Bouke Jul 31 '18 at 12:38