Reputation: 994
I'm creating a DbContext, but I cannot handle storing XML in my database. Is there any other approach than parsing xml to string and saving it as string property in model?
I would like to store my News as XML below:
<News>
<Language value="en-GB">
<Title>Example One</Title>
<Date>25/05/2017 12:12:12</Date>
<Content>Simple <b>HTML</b> content!</Content>
<Miniature>
<File ID="816c9bcc-a9fc-4390-9bdc-52c8a0ae75be">
<Title>File 1</Title>
<Extension>JPG</Extension>
<Path>Server path</Path>
<Thumbnail>Server path to thumbnail</Thumbnail>
</File>
</Miniature>
<Images>
<File ID="bd4c6a21-243f-44cb-9456-7dd596d7ed9f">
<Title>File 2</Title>
<Extension>JPG</Extension>
<Path>Server path</Path>
<Thumbnail>Server path to thumbnail</Thumbnail>
</File>
<File ID="50d4966c-9381-4d28-b289-8a0a8a29433b">
<Title>File 3</Title>
<Extension>PNG</Extension>
<Path>Server path</Path>
<Thumbnail>Server path to thumbnail</Thumbnail>
</File>
</Images>
</Language>
<Language value="en-US">
<Title>Example One</Title>
<Date>25/05/2017 12:12:12</Date>
<Content>
Simple <i>UNITED STATES</i> <b>HTML</b> content!
</Content>
<Miniature>
<File ID="816c9bcc-a9fc-4390-9bdc-52c8a0ae75be">
<Title>File 4</Title>
<Extension>JPG</Extension>
<Path>Server path</Path>
<Thumbnail>Server path to thumbnail</Thumbnail>
</File>
</Miniature>
<Images>
<File ID="bd4c6a21-243f-44cb-9456-7dd596d7ed9f">
<Title>File 2</Title>
<Extension>JPG</Extension>
<Path>Server path</Path>
<Thumbnail>Server path to thumbnail</Thumbnail>
</File>
</Images>
</Language>
</News>
And my File as:
<File>
<Title>File 2</Title>
<Extension>JPG</Extension>
<Path>Server path</Path>
<Thumbnail>Server path to thumbnail</Thumbnail>
</File>
I can simply do this and while doing CRUD operations just parse XML to string and save it in Details:
public class News
{
public Guid ID {get;set;}
public string Details {get;set;}
}
But is there any other way to do this? Like using Serialization attribute or something? How can I achieve that?
Thanks in advance!
Upvotes: 3
Views: 2562
Reputation: 1109
You should use LINQ to XML instead.
XDocument fileXml = XDocument.Load(path);
var files = from files in fileXml.Descendants("File")
select new {
Title = file.Attribute("Title").Value,
Extension = file.Element("Extension").Value,
Path = file.Element("Path").Value,
Thumbnail = file.Element("Thumbnail").Value
};
foreach (var file in files)
{
// Do other operations with each student object
}
Upvotes: 1