1

我認爲這是可能的?基本上我正在接收使用LINQ(LINQ2Entities實體框架)數據並將其返回給IQUERYABLE一旦我需要將這些數據轉換爲XML內存流和硬盤上的物理文件 - streamwriter?將從LINQ(IQueryable)檢索到的數據轉換爲XML?

有誰知道這是可能的嗎?

任何幫助非常感激

我是否需要使用LINQtoXML做到這一點?

任何人都知道的任何示例或教程都很棒。

再次感謝

編輯

經過調查的一點點,我想我需要一個LINQ2Entities XML串行器/ IQueryable的?

回答

2

LINQ to XML可能是最好的選擇。您可以使用functional construction在一個單獨的語句來創建一個XML樹,如:

using (ContactEntities context = new ContactEntities()) { 
    XDocument xml = new XDocument(
     new XElement("contacts", 
      from contact in context.Contacts 
      orderby contact.ContactId 
      select new XElement("contact", 
       new XAttribute("contactId", contact.ContactId), 
       new XElement("firstName", contact.FirstName), 
       new XElement("lastName", contact.LastName)))); 
    xml.Save(yourStream); 
} 
+0

謝謝!但是,這是使用LINQtoXML創建XML,我將如何將IQUERYABLE(來自LINQ2ENTITIES)中的數據(已經存在於SQL Server中)轉換爲XML。 – Martin 2010-11-07 08:27:01

+0

@Martin,你只需要從'IQueryable'投影數據。我試圖在我編輯的答案中反映出這一點。 – 2010-11-07 08:36:08

+0

謝謝!正是我需要的 – Martin 2010-11-22 13:16:32

0

我知道這個問題是舊的,但我想顯示我的解決方案,以解決這個問題。

public static string CreateXml<T>(IQueryable<T> thisQueryable) 
    { 
     var thisList = thisQueryable.ToList(); 
     var xmlResult = ""; 
     using (var stringWriter = new StringWriter()) 
     { 
      using (var xmlWriter = new XmlTextWriter(stringWriter)) 
      { 
       var serializer = new XmlSerializer(typeof(List<T>)); 
       serializer.Serialize(xmlWriter, thisList); 
      } 
      xmlResult = stringWriter.ToString(); 
     } 
     return xmlResult; 
    } 

基本上這只是需要您的IQueryable<T>並序列化爲XML並返回XMLstring

然後,你基本上採取串並....

var xmlDoc = new XmlDocument(); 
xmlDoc.Load(xmlResult); 

希望這有助於爲今後的任何遊客。