2017-05-25 87 views
0

我正在創建一個DbContext,但我無法處理在我的數據庫中存儲XML。除解析xml以將字符串屬性保存爲模型還有其他方法嗎?實體框架 - 如何在數據庫中存儲XML

我想我的新聞存儲如下XML:

<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> 

而且我的文件爲:

<File> 
    <Title>File 2</Title> 
    <Extension>JPG</Extension> 
    <Path>Server path</Path> 
    <Thumbnail>Server path to thumbnail</Thumbnail> 
</File> 

我可以簡單地做到這一點,而這樣做的CRUD操作只是解析XML字符串和保存在詳細信息:

public class News 
{ 
    public Guid ID {get;set;} 
    public string Details {get;set;} 
} 

但是有沒有其他方法可以做到這一點?像使用序列化屬性或什麼的?我怎樣才能做到這一點?

在此先感謝!

+0

序列化是這樣做的,它將xml對象解析爲字符串。 –

+0

但是,我應該如何看待我的新聞課堂和模特? – Ashiv3r

+0

是否與您的xml dtd相同? –

回答

0

您應該改用LINQ to XML

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 
} 
+0

我知道如何操作XML文件,但我不想將它作爲XML文件存儲在我的服務器上,而是作爲數據庫中的XML列存儲。 – Ashiv3r

+0

你是什麼意思?「我不想將它作爲XML文件存儲在我的服務器上,而是作爲數據庫中的XML列」? – Fahadsk

+0

你的答案是關於從路徑讀取XML文件。我不想這樣做,我想從數據庫中讀取它。在SQL中,您可以使用XML類型的列。如何將它作爲XML列存儲在實體框架中? – Ashiv3r