2015-06-30 49 views
0

假設我的例子實體TeamPlayer看起來是這樣的:使用LINQ變換實體以XML

PlayerId PlayerName Team  Position 
---------------------------------------------- 
1   Nobody  Team A  Striker 
1   Nobody  Team B  Center Midfield 
1   Nobody  Team C  Substitute 
2   Chuck Norris TeamA  ALL 
2   Chuck Norris TeamB  Substitute 

什麼,我試圖做到的,是寫一個C#方法,其中我通過玩家ID。結果應該是這樣的一個XML字符串(如果1被傳遞給方法):

<ns0:root xmlns:ns0="urn:teamsoftware:playermanager:playerovierview"> 
    <player> 
     <playerid>1</playerid> 
     <playername>Nobody</playername> 
     <team>TeamA 
TeamB 
TeamC</team> 
     <position>Striker 
Center Midfield 
Substiture</position> 
    </player> 
</ns0:root> 

所以,如果一個玩家加入更多的球隊,他們應該是裏面<team>標籤,通過CR LF分隔。我知道這是一個醜陋的解決方案,但數據被傳送到第三方工具,所以他們必須看起來像這樣不幸:/

任何幫助表示讚賞!

+0

你有什麼到目前爲止編碼?我們可以幫助哪些部分? – Tikkes

+0

那麼你有一些'列表'或類似的查詢這個數據? –

回答

2

醜陋的,因爲使用string.Join來創建適當的文本內容並不難。我以爲你知道該怎麼做 - - 獲取的相關數據後,你可以只使用類似:

var records = ...; // The player records 
XNamespace ns = "urn:teamsoftware:playermanager:playerovierview"; 
return new XElement(ns + "root", 
    new XElement("player", 
     new XElement("playerid", records.First().PlayerId), 
     new XElement("playername", records.First().PlayerName), 
     new XElement("team", string.Join("\r\n", records.Select(x => x.Team)), 
     new XElement("position", string.Join("\r\n", records.Select(x => x.Position)) 
    ) 
); 
+0

如果示例XML正確,那麼'root'的所有子節點都沒有名稱空間。 –

+0

@CharlesMager:哎呀,你是對的。固定。 –

+0

感謝您的回答 - 但我收到了錯誤消息,比如'TeamPlayer'沒有包含'Select'的定義,並且沒有找到接受'TeamPlayer'類型的第一個參數的擴展方法'Select'使用僞指令或程序集引用?)出現在團隊名稱應該加入的行中:/ – CeOnSql

0

我會用下面的代碼

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data; 

namespace ConsoleApplication34 
{ 
    class Program 
    { 
     const string FILENAME = @"C:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      DataTable dt = new DataTable(); 
      dt.Columns.Add("PlayerId", typeof(int)); 
      dt.Columns.Add("PlayerName", typeof(string)); 
      dt.Columns.Add("Team", typeof(string)); 
      dt.Columns.Add("Postition", typeof(string)); 

      dt.Rows.Add(new object[] {1,"Nobody", "Team A", "Striker"}); 
      dt.Rows.Add(new object[] {1,"Nobody", "Team B", "Center Midfield"}); 
      dt.Rows.Add(new object[] {1,"Nobody", "Team C", "Substitute"}); 
      dt.Rows.Add(new object[] {2,"Chuck Norris", "Team A", "ALL"}); 
      dt.Rows.Add(new object[] {2,"Chuck Norris", "Team B", "Substitute"}); 

      DataTable results = dt.AsEnumerable() 
       .Where(x => x.Field<int>("PlayerId") == 1).ToList().CopyToDataTable(); 

      DataSet ds = new DataSet(); 
      ds.Tables.Add(results); 
      ds.WriteXml(FILENAME, XmlWriteMode.WriteSchema); 

     } 

    } 
}