簡體   English   中英

實體框架-如何在數據庫中存儲XML

[英]Entity Framework - how to store XML in database

我正在創建DbContext,但是無法處理在數據庫中存儲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解析為字符串並將其保存在Details中即可:

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

但是還有其他方法嗎? 喜歡使用序列化屬性或其他東西? 我該如何實現?

提前致謝!

您應該改為使用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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM